mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::io::{self, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};

use crate::mxc_common::logger::Logger;
use crate::mxc_common::mxc_error::{MxcError, MxcErrorCode};
use crate::mxc_common::script_runner::RunCancellation;
use aci_edge_sandboxes::agent::{
    AgentBackend, AgentConfig, BundledAgent, CpuProfile, ImageDigest, PlatformSnapshots,
    SandboxDiagnostics, SetupConfig,
};
use aci_edge_sandboxes::{
    AciEdgeSandbox, Backend, Capabilities, Error, ErrorCode, ExecIo, ExecOutcome, ExecRequest,
    ImageSource, OutputCloser, OutputSink, ProvisionRequest, SandboxSpec, StartResult,
};

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct SandboxId(aci_edge_sandboxes::SandboxId);

impl SandboxId {
    pub fn from_token(token: &str) -> aci_edge_sandboxes::Result<Self> {
        aci_edge_sandboxes::SandboxId::from_token(token).map(Self)
    }

    pub fn from_mxc(value: &str) -> Result<Self, MxcError> {
        let token = value.strip_prefix("microvm:").ok_or_else(|| {
            MxcError::malformed_id("MicroVM sandbox ID must start with 'microvm:'")
        })?;
        Self::from_token(token).map_err(|_| {
            MxcError::malformed_id(
                "MicroVM sandbox ID must contain 32 lowercase hexadecimal digits",
            )
        })
    }

    pub fn to_mxc_string(&self) -> String {
        format!("microvm:{}", self.0.token())
    }
}

impl std::fmt::Display for SandboxId {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.0, formatter)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct ProvisionOutput {
    pub sandbox_id: SandboxId,
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
}

pub(super) const CAPTURE_LIMIT_BYTES: usize = 64 * 1024 * 1024;
const STARTUP_LOG_LIMIT: usize = 8 * 1024;
const HOST_TIMEOUT_SLACK_MS: u64 = 30_000;
const POLL: Duration = Duration::from_millis(100);
const CANCEL_GRACE: Duration = Duration::from_secs(2);
pub(super) const UNKNOWN_OUTCOME: &str =
    "NVX execution outcome is unknown after the 2-second cancellation grace period; \
     the workload may still be running";
pub(super) const CANCEL_UNFINISHED: &str =
    "NVX cancellation did not finish within the 2-second grace period; \
     a background native call may still be running";

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct PreparedProvision {
    pub request: ProvisionRequest,
    pub spec: SandboxSpec,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct ExecOutput {
    pub outcome: ExecOutcome,
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
}

pub(super) trait SandboxClient {
    fn capabilities(&self) -> Result<Capabilities, MxcError>;
    fn validate_provision(&self, input: &PreparedProvision) -> Result<(), MxcError>;
    fn validate_exec(&self, request: &ExecRequest) -> Result<(), MxcError>;
    /// Opens the process-owned execution host, returning a cold-boot fallback reason if template
    /// initialization is unavailable. Invalid setup and handle-close failures remain errors.
    fn open_execution_host(&mut self) -> Result<Option<MxcError>, MxcError>;
    fn probe(&self) -> Result<(), MxcError>;
    fn provision(&self, input: &PreparedProvision) -> Result<ProvisionOutput, MxcError>;
    fn start(&self, sandbox_id: &SandboxId) -> Result<StartResult, MxcError>;
    fn diagnostics(&self, sandbox_id: &SandboxId) -> Result<SandboxDiagnostics, MxcError>;
    fn exec_and_wait(
        &self,
        sandbox_id: &SandboxId,
        request: &ExecRequest,
        cancellation: Option<&RunCancellation>,
        logger: &mut Logger,
    ) -> Result<ExecOutput, MxcError>;
    fn stop(&self, sandbox_id: &SandboxId) -> Result<(), MxcError>;
    fn deprovision(&self, sandbox_id: &SandboxId) -> Result<(), MxcError>;
    fn close(&mut self) -> Result<(), MxcError>;
}

pub(super) fn startup_diagnostics(diagnostics: &SandboxDiagnostics) -> String {
    let mut excerpt = String::new();
    for (name, path) in [
        ("vmm_log", &diagnostics.vmm_log),
        ("console_log", &diagnostics.console_log),
        ("outcome_report", &diagnostics.outcome_report),
    ] {
        excerpt.push_str(&format!("; {name}: "));
        match read_startup_log(path) {
            Ok((bytes, truncated)) => {
                if truncated {
                    excerpt.push_str("[truncated] ");
                }
                if bytes.is_empty() {
                    excerpt.push_str("[empty]");
                } else {
                    excerpt.push_str(&String::from_utf8_lossy(&bytes));
                }
            }
            Err(error) => excerpt.push_str(&format!("unavailable ({}): {error}", path.display())),
        }
    }
    excerpt
}

fn read_startup_log(path: &Path) -> io::Result<(Vec<u8>, bool)> {
    let mut file = std::fs::File::open(path)?;
    let length = file.metadata()?.len();
    let start = length.saturating_sub(STARTUP_LOG_LIMIT as u64);
    file.seek(SeekFrom::Start(start))?;
    let mut bytes = Vec::new();
    file.take(STARTUP_LOG_LIMIT as u64 + 1)
        .read_to_end(&mut bytes)?;
    let truncated = start != 0 || bytes.len() > STARTUP_LOG_LIMIT;
    bytes.truncate(STARTUP_LOG_LIMIT);
    Ok((bytes, truncated))
}

pub(super) fn map_error(error: Error) -> MxcError {
    let code = match error.code() {
        ErrorCode::MalformedRequest => MxcErrorCode::MalformedRequest,
        ErrorCode::MalformedId => MxcErrorCode::MalformedId,
        ErrorCode::StaleId => MxcErrorCode::StaleId,
        ErrorCode::NotStarted => MxcErrorCode::NotStarted,
        ErrorCode::AlreadyStarted => MxcErrorCode::AlreadyStarted,
        ErrorCode::AlreadyStopped => MxcErrorCode::AlreadyStopped,
        ErrorCode::PolicyValidation => MxcErrorCode::PolicyValidation,
        ErrorCode::BackendUnavailable => MxcErrorCode::BackendUnavailable,
        ErrorCode::Unsupported | ErrorCode::BackendError => MxcErrorCode::BackendError,
        _ => MxcErrorCode::BackendError,
    };
    let mut message = format!("NVX signed bundled agent: {error}");
    let mut source = std::error::Error::source(&error);
    while let Some(cause) = source {
        message.push_str(&format!(": {cause}"));
        source = cause.source();
    }
    MxcError::new(code, message)
}

pub(super) fn sandbox_spec(image: &str) -> Result<SandboxSpec, MxcError> {
    crate::mxc_contract::dev::ImageReference::validate(image)
        .map_err(MxcError::malformed_request)?;
    Ok(SandboxSpec::new().with_image(ImageSource::Reference(image.to_owned())))
}

struct ClientInner {
    backend: Arc<AgentBackend>,
    client: AciEdgeSandbox,
    _state_root_guard: Option<crate::mxc_common::filesystem_security::LockedDirectoryPath>,
}

pub(super) struct NvxClient(Option<ClientInner>);

// Sandboxes have the agent's default resources, one virtual processor and 256 MiB of memory,
// unless a request sets their memory, so the smallest templates fit them.
const PLATFORM_SNAPSHOT_MAX_VCPUS: u32 = 1;
const PLATFORM_SNAPSHOT_MAX_MEMORY_MIB: u32 = 256;

fn agent_setup(bundle: &BundledAgent, state_root: &Path) -> SetupConfig {
    bundle.setup(state_root).with_cpu_profile(CpuProfile::Host)
}

static RUNTIME_DIRECTORY: OnceLock<PathBuf> = OnceLock::new();

pub(crate) fn register_runtime_directory(directory: &str) -> Result<(), MxcError> {
    register_directory_in(&RUNTIME_DIRECTORY, directory)
}

fn register_directory_in(storage: &OnceLock<PathBuf>, directory: &str) -> Result<(), MxcError> {
    let path = Path::new(directory);
    if !path.is_absolute() {
        return Err(MxcError::malformed_request(
            "NVX runtime directory must be an absolute path",
        ));
    }
    let canonical = path.canonicalize().map_err(|error| {
        MxcError::backend_unavailable(format!("cannot resolve NVX runtime directory: {error}"))
    })?;
    if !canonical.is_dir() {
        return Err(MxcError::backend_unavailable(
            "NVX runtime path is not a directory",
        ));
    }
    crate::mxc_common::module_lifetime::pin_current_module()
        .map_err(MxcError::backend_unavailable)?;
    let registered = storage.get_or_init(|| canonical.clone());
    if *registered != canonical {
        return Err(MxcError::new(
            MxcErrorCode::PolicyValidation,
            "a different NVX runtime directory is already registered for this process",
        ));
    }
    Ok(())
}

fn discover_bundle() -> Result<BundledAgent, MxcError> {
    let configured = std::env::var_os("ACI_EDGE_SANDBOXES_AGENT_ARTIFACTS_DIR")
        .filter(|value| !value.is_empty())
        .map(PathBuf::from);
    discover_bundle_from(
        configured.as_deref(),
        RUNTIME_DIRECTORY.get().map(PathBuf::as_path),
        || {
            crate::mxc_common::process_util::module_path_for_address(discover_bundle as *const ())
                .map_err(MxcError::backend_unavailable)
        },
    )
}

fn module_candidates(directory: &Path) -> Vec<PathBuf> {
    let mut candidates = vec![directory.join("aci-edge-sandboxes")];
    let mut components = directory.components().rev();
    let is_rid_native = ["native", "win-x64", "runtimes"].iter().all(|expected| {
        components.next().is_some_and(|component| {
            component
                .as_os_str()
                .to_str()
                .is_some_and(|part| part.eq_ignore_ascii_case(expected))
        })
    });
    if is_rid_native {
        if let Some(rid) = directory.parent() {
            candidates.push(rid.join("aci-edge-sandboxes"));
            if let Some(root) = rid.parent().and_then(Path::parent) {
                candidates.push(root.join("aci-edge-sandboxes"));
            }
        }
    }
    candidates
}

// File inventory from the approved SHA256SUMS pinned in signature_verification.
const REQUIRED_BUNDLE_FILES: &[&str] = &[
    r"bin\aci_edge_agent.dll",
    r"bundle-manifest.json",
    r"SOURCE-MANIFEST.json",
    r"SHA256SUMS",
    r"NOTICE.txt",
    r"bin\EULA.txt",
    r"bin\direct-images.exe",
    r"bin\openvmm.exe",
    r"guest\initramfs-edge.cpio.gz",
    r"guest\nvx-edge-agent",
    r"guest\vmlinux",
    r"guest\vmlinux.config",
    r"licenses\linux\COPYING",
    r"licenses\linux\LICENSES\deprecated\0BSD",
    r"licenses\linux\LICENSES\deprecated\CC0-1.0",
    r"licenses\linux\LICENSES\deprecated\GFDL-1.1",
    r"licenses\linux\LICENSES\deprecated\GFDL-1.2",
    r"licenses\linux\LICENSES\deprecated\GPL-1.0",
    r"licenses\linux\LICENSES\deprecated\ISC",
    r"licenses\linux\LICENSES\deprecated\Linux-OpenIB",
    r"licenses\linux\LICENSES\deprecated\X11",
    r"licenses\linux\LICENSES\deprecated\Zlib",
    r"licenses\linux\LICENSES\dual\Apache-2.0",
    r"licenses\linux\LICENSES\dual\CC-BY-4.0",
    r"licenses\linux\LICENSES\dual\CDDL-1.0",
    r"licenses\linux\LICENSES\dual\MPL-1.1",
    r"licenses\linux\LICENSES\dual\copyleft-next-0.3.1",
    r"licenses\linux\LICENSES\exceptions\GCC-exception-2.0",
    r"licenses\linux\LICENSES\exceptions\Linux-syscall-note",
    r"licenses\linux\LICENSES\preferred\BSD-2-Clause",
    r"licenses\linux\LICENSES\preferred\BSD-3-Clause",
    r"licenses\linux\LICENSES\preferred\BSD-3-Clause-Clear",
    r"licenses\linux\LICENSES\preferred\GPL-2.0",
    r"licenses\linux\LICENSES\preferred\LGPL-2.0",
    r"licenses\linux\LICENSES\preferred\LGPL-2.1",
    r"licenses\linux\LICENSES\preferred\MIT",
    r"provenance\direct-images\NOTICE.txt",
    r"provenance\direct-images\SHA256SUMS",
    r"provenance\direct-images\cgmanifest.json",
    r"provenance\direct-images\dependency-inventory.json",
    r"provenance\direct-images\direct-images-manifest.json",
    r"provenance\direct-images\licenses\modules\001\LICENSE",
    r"provenance\direct-images\licenses\modules\002\LICENSE",
    r"provenance\direct-images\licenses\modules\003\LICENSE",
    r"provenance\direct-images\licenses\modules\004\LICENSE.md",
    r"provenance\direct-images\licenses\modules\005\AUTHORS",
    r"provenance\direct-images\licenses\modules\005\LICENSE",
    r"provenance\direct-images\licenses\modules\005\NOTICE",
    r"provenance\direct-images\licenses\modules\005\cli\connhelper\internal\syntax\LICENSE",
    r"provenance\direct-images\licenses\modules\006\LICENSE",
    r"provenance\direct-images\licenses\modules\007\LICENSE",
    r"provenance\direct-images\licenses\modules\008\LICENSE",
    r"provenance\direct-images\licenses\modules\009\LICENSE",
    r"provenance\direct-images\licenses\modules\009\gzhttp\LICENSE",
    r"provenance\direct-images\licenses\modules\009\internal\lz4ref\LICENSE",
    r"provenance\direct-images\licenses\modules\009\internal\snapref\LICENSE",
    r"provenance\direct-images\licenses\modules\009\s2\LICENSE",
    r"provenance\direct-images\licenses\modules\009\s2\cmd\internal\filepathx\LICENSE",
    r"provenance\direct-images\licenses\modules\009\s2\cmd\internal\readahead\LICENSE",
    r"provenance\direct-images\licenses\modules\009\snappy\AUTHORS",
    r"provenance\direct-images\licenses\modules\009\snappy\CONTRIBUTORS",
    r"provenance\direct-images\licenses\modules\009\snappy\LICENSE",
    r"provenance\direct-images\licenses\modules\009\snappy\xerial\LICENSE",
    r"provenance\direct-images\licenses\modules\009\zstd\internal\xxhash\LICENSE.txt",
    r"provenance\direct-images\licenses\modules\010\LICENSE",
    r"provenance\direct-images\licenses\modules\011\LICENSE",
    r"provenance\direct-images\licenses\modules\012\LICENSE",
    r"provenance\direct-images\licenses\modules\012\cmd\runhcs\LICENSE",
    r"provenance\direct-images\licenses\modules\012\cmd\runhcs\NOTICE",
    r"provenance\direct-images\licenses\modules\012\pkg\go-runhcs\LICENSE",
    r"provenance\direct-images\licenses\modules\012\pkg\go-runhcs\NOTICE",
    r"provenance\direct-images\licenses\modules\013\LICENSE.md",
    r"provenance\direct-images\licenses\modules\014\LICENSE",
    r"provenance\direct-images\licenses\modules\014\LICENSE.docs",
    r"provenance\direct-images\licenses\modules\015\LICENSE",
    r"provenance\direct-images\licenses\modules\016\LICENSE",
    r"provenance\direct-images\licenses\modules\017\LICENSE.txt",
    r"provenance\direct-images\licenses\modules\018\LICENSE",
    r"provenance\direct-images\licenses\modules\019\LICENSE",
    r"provenance\direct-images\licenses\modules\020\LICENSE",
    r"provenance\direct-images\licenses\modules\021\AUTHORS",
    r"provenance\direct-images\licenses\modules\021\LICENSE",
    r"provenance\direct-images\licenses\modules\022\LICENSE",
    r"provenance\direct-images\licenses\modules\022\PATENTS",
    r"provenance\direct-images\licenses\modules\023\LICENSE",
    r"provenance\direct-images\licenses\modules\023\PATENTS",
    r"provenance\direct-images\licenses\modules\024\LICENSE",
    r"provenance\direct-images\licenses\modules\024\PATENTS",
    r"provenance\direct-images\licenses\source\EULA.txt",
    r"provenance\direct-images\licenses\toolchain\LICENSE",
    r"provenance\direct-images\licenses\toolchain\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\compile\internal\ssa\_gen\vendor\golang.org\x\tools\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\compile\internal\ssa\_gen\vendor\golang.org\x\tools\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\github.com\google\pprof\AUTHORS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\github.com\google\pprof\CONTRIBUTORS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\github.com\google\pprof\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\github.com\google\pprof\third_party\svgpan\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\github.com\ianlancetaylor\demangle\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\github.com\microsoft\go-infra\telemetry\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\github.com\microsoft\go-infra\telemetry\config\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\arch\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\arch\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\build\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\build\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\mod\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\mod\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\sync\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\sync\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\sys\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\sys\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\telemetry\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\telemetry\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\term\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\term\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\text\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\text\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\tools\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\golang.org\x\tools\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\cmd\vendor\rsc.io\markdown\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\crypto\internal\boring\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\runtime\testdata\testgoroutineleakprofile\goker\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\vendor\github.com\microsoft\go-crypto-darwin\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\vendor\github.com\microsoft\go-crypto-openssl\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\vendor\github.com\microsoft\go-crypto-winnative\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\vendor\golang.org\x\crypto\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\vendor\golang.org\x\crypto\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\vendor\golang.org\x\net\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\vendor\golang.org\x\net\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\vendor\golang.org\x\sys\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\vendor\golang.org\x\sys\PATENTS",
    r"provenance\direct-images\licenses\toolchain\src\vendor\golang.org\x\text\LICENSE",
    r"provenance\direct-images\licenses\toolchain\src\vendor\golang.org\x\text\PATENTS",
    r"provenance\edge-guest.json",
    r"provenance\edge-windows.json",
    r"provenance\licenses\linux\COPYING-LINUX",
    r"provenance\licenses\nvx\LICENSE",
    r"provenance\licenses\nvx\THIRD_PARTY_NOTICES.md",
    r"provenance\licenses\openvmm\LICENSE",
    r"provenance\openvmm.provenance.json",
    r"provenance\vmlinux.provenance.json",
    r"source\linux\BUILD-ENVIRONMENT.txt",
    r"source\linux\SOURCE-MANIFEST.json",
    r"source\linux\SOURCE.md",
    r"source\linux\config-microvm",
    r"source\linux\patches\0001-microvm-xe9-earlycon.patch",
    r"source\linux\patches\0002-microvm-hvc-xe9.patch",
    r"source\linux\patches\0003-microvm-virtio-mmio-shared-status.patch",
];

fn selected_bundle_with(
    directory: &Path,
    is_file: &impl Fn(&Path) -> bool,
) -> Result<BundledAgent, MxcError> {
    let bundle = BundledAgent::from_dir(directory).map_err(map_error)?;
    for relative_path in REQUIRED_BUNDLE_FILES {
        let path = directory.join(relative_path);
        if !is_file(&path) {
            return Err(MxcError::backend_unavailable(format!(
                "NVX bundle is missing {}",
                path.display()
            )));
        }
    }
    Ok(bundle)
}

fn module_candidate_exists(candidate: &Path) -> Result<bool, MxcError> {
    match std::fs::symlink_metadata(candidate) {
        Ok(_) => Ok(true),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(MxcError::backend_unavailable(format!(
            "cannot inspect NVX runtime directory {}: {error}",
            candidate.display()
        ))),
    }
}

fn require_module_directory(candidate: &Path) -> Result<(), MxcError> {
    let metadata = std::fs::metadata(candidate).map_err(|error| {
        MxcError::backend_unavailable(format!(
            "cannot resolve NVX runtime directory {}: {error}",
            candidate.display()
        ))
    })?;
    if !metadata.is_dir() {
        return Err(MxcError::backend_unavailable(format!(
            "NVX runtime path {} is not a directory",
            candidate.display()
        )));
    }
    Ok(())
}

fn discover_bundle_from(
    configured: Option<&Path>,
    registered: Option<&Path>,
    module_path: impl FnOnce() -> Result<PathBuf, MxcError>,
) -> Result<BundledAgent, MxcError> {
    discover_bundle_from_with(
        configured,
        registered,
        module_path,
        &module_candidate_exists,
        &require_module_directory,
        &Path::is_file,
    )
}

fn discover_bundle_from_with(
    configured: Option<&Path>,
    registered: Option<&Path>,
    module_path: impl FnOnce() -> Result<PathBuf, MxcError>,
    candidate_exists: &impl Fn(&Path) -> Result<bool, MxcError>,
    require_directory: &impl Fn(&Path) -> Result<(), MxcError>,
    is_file: &impl Fn(&Path) -> bool,
) -> Result<BundledAgent, MxcError> {
    if let Some(directory) = configured.or(registered) {
        return selected_bundle_with(directory, is_file);
    }
    let module = module_path()?;
    let directory = module.parent().ok_or_else(|| {
        MxcError::backend_unavailable("the native module has no parent directory")
    })?;
    for candidate in module_candidates(directory) {
        if candidate_exists(&candidate)? {
            require_directory(&candidate)?;
            return selected_bundle_with(&candidate, is_file);
        }
    }
    let bundle = BundledAgent::discover().map_err(map_error)?;
    selected_bundle_with(bundle.directory(), is_file)
}

fn platform_snapshots() -> PlatformSnapshots {
    PlatformSnapshots::new(
        PLATFORM_SNAPSHOT_MAX_VCPUS,
        PLATFORM_SNAPSHOT_MAX_MEMORY_MIB,
    )
}

/// Opens the agent without platform snapshots, so opening it never boots a VM.
pub(super) fn create_persistent_client(
    guard: crate::mxc_common::filesystem_security::LockedDirectoryPath,
) -> Result<NvxClient, MxcError> {
    let path = guard.path().to_path_buf();
    create_client_with_guard(&path, Some(guard))
}

fn create_client_with_guard(
    state_root: &Path,
    guard: Option<crate::mxc_common::filesystem_security::LockedDirectoryPath>,
) -> Result<NvxClient, MxcError> {
    let bundle = discover_bundle()?;
    let directory = bundle.directory().canonicalize().map_err(|error| {
        MxcError::backend_unavailable(format!("cannot resolve NVX bundle: {error}"))
    })?;
    let bundle = BundledAgent::from_dir(directory).map_err(map_error)?;
    // The crate's output pump can outlive an unknown execution outcome and client teardown.
    crate::mxc_common::module_lifetime::pin_current_module()
        .map_err(MxcError::backend_unavailable)?;
    let config = bundle.config(agent_setup(&bundle, state_root));
    let backend = Arc::new(AgentBackend::new(config).map_err(map_error)?);
    let client = AciEdgeSandbox::from_shared(backend.clone());
    Ok(NvxClient(Some(ClientInner {
        backend,
        client,
        _state_root_guard: guard,
    })))
}

impl NvxClient {
    fn inner(&self) -> Result<&ClientInner, MxcError> {
        self.0
            .as_ref()
            .ok_or_else(|| MxcError::backend_error("NVX client is closed"))
    }
}

pub(super) fn agent_bundle_available() -> bool {
    discover_bundle().is_ok_and(|bundle| bundle.library().is_file())
}

pub(super) fn require_agent_bundle_present() -> Result<(), MxcError> {
    let bundle = discover_bundle()?;
    if bundle.library().is_file() {
        Ok(())
    } else {
        Err(MxcError::backend_unavailable(format!(
            "NVX bundle is missing {}",
            bundle.library().display()
        )))
    }
}

pub(super) fn state_root(
) -> Result<crate::mxc_common::filesystem_security::LockedDirectoryPath, MxcError> {
    let local_app_data = std::env::var_os("LOCALAPPDATA")
        .filter(|value| !value.is_empty())
        .map(std::path::PathBuf::from)
        .or_else(|| {
            std::env::var_os("USERPROFILE")
                .filter(|value| !value.is_empty())
                .map(|profile| std::path::PathBuf::from(profile).join("AppData").join("Local"))
        })
        .ok_or_else(|| {
            MxcError::backend_unavailable(
                "NVX signed bundled agent: cannot resolve LOCALAPPDATA for the agent state directory",
            )
        })?;
    let bundle = discover_bundle()?;
    state_root_in(&local_app_data, bundle.manifest_sha256())
}

fn state_root_in(
    local_app_data: &Path,
    manifest_sha256: [u8; 32],
) -> Result<crate::mxc_common::filesystem_security::LockedDirectoryPath, MxcError> {
    let local_app_data = std::path::absolute(local_app_data).map_err(|error| {
        MxcError::backend_unavailable(format!(
            "NVX signed bundled agent: cannot resolve the agent state directory: {error}"
        ))
    })?;
    let parent = lock_lifecycle_state_root_in(&local_app_data)?;
    let bundle_key: String = manifest_sha256[..8]
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect();
    let root = crate::mxc_common::filesystem_security::lock_owner_only_directory_path(
        parent.path(),
        &[std::ffi::OsStr::new(&bundle_key)],
        0,
    )
    .map_err(|error| {
        MxcError::backend_unavailable(format!(
            "NVX signed bundled agent: cannot create the bundle state directory below '{}': {error}",
            parent.path().display()
        ))
    })?;
    crate::mxc_common::filesystem_security::set_current_user_owner(root.path()).map_err(
        |error| {
            MxcError::backend_unavailable(format!(
                "NVX signed bundled agent: cannot secure the bundle state directory {}: {error}",
                root.path().display()
            ))
        },
    )?;
    Ok(root)
}

pub(super) fn lifecycle_state_root(
) -> Result<crate::mxc_common::filesystem_security::LockedDirectoryPath, MxcError> {
    let local_app_data = std::env::var_os("LOCALAPPDATA").ok_or_else(|| {
        MxcError::backend_unavailable(
            "cannot resolve LOCALAPPDATA for the persistent NVX lifecycle state",
        )
    })?;
    let local_app_data = std::path::PathBuf::from(local_app_data);
    lock_lifecycle_state_root_in(&local_app_data)
}

fn lock_lifecycle_state_root_in(
    local_app_data: &Path,
) -> Result<crate::mxc_common::filesystem_security::LockedDirectoryPath, MxcError> {
    let root = crate::mxc_common::filesystem_security::lock_owner_only_directory_path(
        local_app_data,
        [
            std::ffi::OsStr::new("Microsoft"),
            std::ffi::OsStr::new("MXC"),
            std::ffi::OsStr::new("nvx"),
        ]
        .as_slice(),
        2,
    )
    .map_err(|error| {
        MxcError::backend_unavailable(format!(
            "cannot admit persistent NVX state below '{}': {error}",
            local_app_data.display()
        ))
    })?;
    crate::mxc_common::filesystem_security::set_current_user_owner(root.path()).map_err(
        |error| {
            MxcError::backend_unavailable(format!(
                "cannot make the current user the owner of persistent NVX state '{}': {error}",
                root.path().display()
            ))
        },
    )?;
    Ok(root)
}

pub(super) enum Event {
    Stdout(Vec<u8>),
    Stderr(Vec<u8>),
    Exit(Result<ExecOutcome, MxcError>),
}

struct EventSink {
    sender: mpsc::SyncSender<Event>,
    closed: Arc<AtomicBool>,
    stderr: bool,
}

impl OutputSink for EventSink {
    fn write(&mut self, data: &[u8]) -> io::Result<()> {
        // Bound buffering even when the caller holds its output without reading.
        for bytes in data.chunks(64 * 1024) {
            let mut event = if self.stderr {
                Event::Stderr(bytes.to_vec())
            } else {
                Event::Stdout(bytes.to_vec())
            };
            loop {
                if self.closed.load(Ordering::Acquire) {
                    return Err(io::ErrorKind::BrokenPipe.into());
                }
                match self.sender.try_send(event) {
                    Ok(()) => break,
                    Err(mpsc::TrySendError::Full(pending)) => {
                        event = pending;
                        std::thread::sleep(Duration::from_millis(10));
                    }
                    Err(mpsc::TrySendError::Disconnected(_)) => {
                        return Err(io::ErrorKind::BrokenPipe.into())
                    }
                }
            }
        }
        Ok(())
    }

    fn close_handle(&self) -> Option<OutputCloser> {
        let closed = self.closed.clone();
        Some(OutputCloser::new(move || {
            closed.store(true, Ordering::Release)
        }))
    }
}

#[derive(Clone)]
pub(super) struct StreamingExecution(Arc<StreamingExecutionInner>);

struct StreamingExecutionInner {
    control: Arc<dyn aci_edge_sandboxes::ExecControl>,
    receiver: Mutex<Option<mpsc::Receiver<Event>>>,
    closed: Arc<AtomicBool>,
    cancellation: Mutex<Option<Instant>>,
}

impl NvxClient {
    pub(super) fn start_execution(
        &self,
        sandbox_id: &SandboxId,
        request: &ExecRequest,
    ) -> Result<StreamingExecution, MxcError> {
        let inner = self.inner()?;
        let (sender, receiver) = mpsc::sync_channel(1);
        let closed = Arc::new(AtomicBool::new(false));
        let io = ExecIo {
            stdout: Box::new(EventSink {
                sender: sender.clone(),
                closed: closed.clone(),
                stderr: false,
            }),
            stderr: Box::new(EventSink {
                sender: sender.clone(),
                closed: closed.clone(),
                stderr: true,
            }),
            stdin: None,
        };
        let control: Arc<dyn aci_edge_sandboxes::ExecControl> = Arc::from(
            inner
                .backend
                .exec(&sandbox_id.0, request, io)
                .map_err(map_error)?,
        );
        StreamingExecution::observe(control, sender, receiver, closed)
    }
}

impl StreamingExecution {
    fn observe(
        control: Arc<dyn aci_edge_sandboxes::ExecControl>,
        sender: mpsc::SyncSender<Event>,
        receiver: mpsc::Receiver<Event>,
        closed: Arc<AtomicBool>,
    ) -> Result<Self, MxcError> {
        let waiting = control.clone();
        if let Err(error) = std::thread::Builder::new()
            .name("mxc-nvx-stream".to_owned())
            .spawn(move || {
                let _ = sender.send(Event::Exit(waiting.wait().map_err(map_error)));
            })
        {
            closed.store(true, Ordering::Release);
            return Err(MxcError::backend_error(format!(
                "cannot start NVX stream observer: {error}; execution outcome is unknown"
            )));
        }
        Ok(Self(Arc::new(StreamingExecutionInner {
            control,
            receiver: Mutex::new(Some(receiver)),
            closed,
            cancellation: Mutex::new(None),
        })))
    }
    pub(super) fn next<T>(
        &self,
        timeout_ms: Option<u64>,
        deliver: impl FnOnce(Event) -> T,
    ) -> Result<Option<T>, MxcError> {
        let deadline = timeout_ms
            .and_then(|timeout| Instant::now().checked_add(Duration::from_millis(timeout)));
        let receiver = self
            .0
            .receiver
            .lock()
            .map_err(|_| MxcError::backend_error("NVX stream receiver lock poisoned"))?;
        let receiver = receiver
            .as_ref()
            .ok_or_else(|| MxcError::backend_error("NVX execution was released"))?;
        loop {
            let cancelled = *self
                .0
                .cancellation
                .lock()
                .map_err(|_| MxcError::backend_error("NVX cancellation lock poisoned"))?;
            if cancelled.is_some_and(|start| start.elapsed() >= CANCEL_GRACE) {
                return Err(MxcError::backend_error(UNKNOWN_OUTCOME));
            }
            let pause = deadline.map_or(POLL, |end| {
                POLL.min(end.saturating_duration_since(Instant::now()))
            });
            match receiver.recv_timeout(pause) {
                Ok(event) => return Ok(Some(deliver(event))),
                Err(mpsc::RecvTimeoutError::Disconnected) => {
                    return Err(MxcError::backend_error(
                        "NVX stream ended without an outcome",
                    ))
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    if deadline.is_some_and(|end| Instant::now() >= end) {
                        return Ok(None);
                    }
                }
            }
        }
    }

    pub(super) fn cancel(&self) -> Result<(), MxcError> {
        {
            let mut cancelled = self
                .0
                .cancellation
                .lock()
                .map_err(|_| MxcError::backend_error("NVX cancellation lock poisoned"))?;
            if cancelled.is_some() {
                return Ok(());
            }
            *cancelled = Some(Instant::now());
        }
        self.0.closed.store(true, Ordering::Release);
        let control = self.0.control.clone();
        let (sender, receiver) = mpsc::channel();
        std::thread::Builder::new()
            .name("mxc-nvx-stream-cancel".to_owned())
            .spawn(move || {
                let _ = sender.send(control.cancel().map_err(map_error));
            })
            .map_err(|error| {
                MxcError::backend_error(format!("cannot start NVX cancellation worker: {error}"))
            })?;
        receiver
            .recv_timeout(CANCEL_GRACE)
            .map_err(|_| MxcError::backend_error(CANCEL_UNFINISHED))?
    }

    pub(super) fn release(&self) -> Result<(), MxcError> {
        self.0.closed.store(true, Ordering::Release);
        self.0
            .receiver
            .lock()
            .map_err(|_| MxcError::backend_error("NVX stream receiver lock poisoned"))?
            .take();
        Ok(())
    }
}

impl Drop for StreamingExecutionInner {
    fn drop(&mut self) {
        self.closed.store(true, Ordering::Release);
    }
}

#[derive(Default)]
struct Captured {
    stdout: Vec<u8>,
    stderr: Vec<u8>,
    overflow: bool,
}

struct CaptureSink {
    shared: Arc<Mutex<Captured>>,
    stderr: bool,
    limit: usize,
}

impl OutputSink for CaptureSink {
    fn write(&mut self, data: &[u8]) -> io::Result<()> {
        let mut captured = self
            .shared
            .lock()
            .map_err(|_| io::Error::other("NVX capture lock poisoned"))?;
        if data.len()
            > self
                .limit
                .saturating_sub(captured.stdout.len() + captured.stderr.len())
        {
            captured.overflow = true;
            return Err(io::Error::other("NVX capture limit exceeded"));
        }
        if self.stderr {
            captured.stderr.extend_from_slice(data);
        } else {
            captured.stdout.extend_from_slice(data);
        }
        Ok(())
    }
}

pub(super) fn capture_limit_error(limit: usize) -> MxcError {
    MxcError::backend_error(format!(
        "NVX signed bundled agent: combined stdout/stderr capture limit of {limit} bytes exceeded"
    ))
}

fn execution_failure(primary: Option<MxcError>, cleanup: MxcError) -> MxcError {
    match primary {
        Some(mut primary) => {
            primary
                .message
                .push_str(&format!("; cleanup failure: {cleanup}"));
            primary
        }
        None => cleanup,
    }
}

fn collect_execution(
    control: Arc<dyn aci_edge_sandboxes::ExecControl>,
    captured: Arc<Mutex<Captured>>,
    deadline: Option<Instant>,
    cancellation: Option<&RunCancellation>,
    limit: usize,
) -> Result<ExecOutput, MxcError> {
    let (sender, receiver) = mpsc::channel();
    let waiting = control.clone();
    // Workers retain their controls; the caller must not join an unresponsive native call.
    let _waiter = std::thread::Builder::new()
        .name("mxc-nvx-wait".to_owned())
        .spawn(move || {
            let _ = sender.send(waiting.wait());
        })
        .map_err(|error| {
            MxcError::backend_error(format!(
                "cannot start NVX wait thread: {error}; execution outcome is unknown"
            ))
        })?;
    let mut failure = None;
    let mut host_timeout = false;
    let mut observed = None;
    let mut cancel_deadline: Option<Instant> = None;
    let mut cancel_result: Option<mpsc::Receiver<Result<(), MxcError>>> = None;
    let outcome = loop {
        match cancel_result.as_ref().map(mpsc::Receiver::try_recv) {
            Some(Ok(result)) => {
                cancel_result = None;
                if let Err(error) = result {
                    failure = Some(execution_failure(failure, error));
                }
            }
            Some(Err(mpsc::TryRecvError::Disconnected)) => {
                cancel_result = None;
                failure = Some(execution_failure(
                    failure,
                    MxcError::backend_error("NVX cancellation worker terminated without a result"),
                ));
            }
            Some(Err(mpsc::TryRecvError::Empty)) | None => {}
        }
        if cancel_result.is_none() {
            if let Some(outcome) = observed.take() {
                break outcome;
            }
        }
        if cancel_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
            let message = if observed.is_some() {
                CANCEL_UNFINISHED
            } else {
                UNKNOWN_OUTCOME
            };
            // Do not wait for capture locks or worker destruction after this deadline.
            let mut error = MxcError::backend_error(message);
            if let Some(primary) = failure {
                error = execution_failure(Some(error), primary);
            }
            if let Some(Err(native)) = observed {
                error = execution_failure(Some(error), native);
            }
            return Err(error);
        }
        let pause = cancel_deadline.map_or(POLL, |deadline| {
            POLL.min(deadline.saturating_duration_since(Instant::now()))
        });
        if observed.is_none() {
            match receiver.recv_timeout(pause) {
                Ok(result) => observed = Some(result.map_err(map_error)),
                Err(mpsc::RecvTimeoutError::Disconnected) => {
                    observed = Some(Err(MxcError::backend_error(
                        "NVX wait thread terminated without an outcome",
                    )));
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {}
            }
        } else {
            std::thread::sleep(pause);
        }
        if observed.is_some() {
            continue;
        }
        if cancel_deadline.is_none() {
            match captured.lock() {
                Ok(capture) if capture.overflow => failure = Some(capture_limit_error(limit)),
                Err(_) => failure = Some(MxcError::backend_error("NVX capture lock poisoned")),
                _ => {}
            }
            if failure.is_none() {
                if let Some(cancellation) = cancellation {
                    failure = cancellation.check().err();
                }
            }
            if failure.is_none() && deadline.is_some_and(|deadline| Instant::now() >= deadline) {
                host_timeout = true;
            }
            if failure.is_some() || host_timeout {
                cancel_deadline = Some(Instant::now() + CANCEL_GRACE);
                let cancelling = control.clone();
                let (sender, receiver) = mpsc::channel();
                match std::thread::Builder::new()
                    .name("mxc-nvx-cancel".to_owned())
                    .spawn(move || {
                        let _ = sender.send(cancelling.cancel().map_err(map_error));
                    }) {
                    Ok(_worker) => cancel_result = Some(receiver),
                    Err(error) => {
                        failure = Some(execution_failure(
                            failure,
                            MxcError::backend_error(format!(
                                "cannot start NVX cancellation worker: {error}"
                            )),
                        ));
                    }
                }
            }
        }
    };
    let mut captured = captured
        .lock()
        .map_err(|_| MxcError::backend_error("NVX capture lock poisoned"))?;
    if captured.overflow && failure.is_none() {
        failure = Some(capture_limit_error(limit));
    }
    if let Some(mut error) = failure {
        if let Err(cleanup) = outcome {
            error
                .message
                .push_str(&format!("; cleanup failure: {cleanup}"));
        }
        return Err(error);
    }
    let outcome = outcome?;
    Ok(ExecOutput {
        outcome: if host_timeout
            && matches!(outcome, ExecOutcome::Cancelled | ExecOutcome::TimedOut)
        {
            ExecOutcome::TimedOut
        } else {
            outcome
        },
        stdout: std::mem::take(&mut captured.stdout),
        stderr: std::mem::take(&mut captured.stderr),
    })
}

impl SandboxClient for NvxClient {
    fn capabilities(&self) -> Result<Capabilities, MxcError> {
        Ok(self.inner()?.client.capabilities())
    }
    fn validate_provision(&self, input: &PreparedProvision) -> Result<(), MxcError> {
        self.inner()?
            .client
            .validate_provision_with(&input.request, &input.spec)
            .map_err(map_error)
    }
    fn validate_exec(&self, request: &ExecRequest) -> Result<(), MxcError> {
        self.inner()?
            .client
            .validate_exec(request)
            .map_err(map_error)
    }
    fn open_execution_host(&mut self) -> Result<Option<MxcError>, MxcError> {
        let inner = self
            .0
            .as_mut()
            .ok_or_else(|| MxcError::backend_error("NVX client is closed"))?;
        let cold = inner.backend.config();
        let setup = cold
            .setup
            .clone()
            .with_platform_snapshots(platform_snapshots());
        setup.validate().map_err(map_error)?;
        let config = AgentConfig::new(setup, cold.library.clone(), cold.library_sha256);
        // The native library retains hosts by setup for the process lifetime, including after this
        // operation's handle closes. Keep this setup stable rather than adding another cache.
        let backend = match AgentBackend::new(config) {
            Ok(backend) => Arc::new(backend),
            Err(error)
                if matches!(
                    error.code(),
                    ErrorCode::BackendUnavailable
                        | ErrorCode::BackendError
                        | ErrorCode::Unsupported
                ) =>
            {
                return Ok(Some(map_error(error)));
            }
            Err(error) => return Err(map_error(error)),
        };
        inner.client = AciEdgeSandbox::from_shared(backend.clone());
        let cold = std::mem::replace(&mut inner.backend, backend);
        Arc::try_unwrap(cold)
            .map_err(|_| {
                MxcError::backend_error(
                    "cannot close the NVX agent opened without platform snapshots: backend \
                     still has other owners",
                )
            })?
            .close()
            .map_err(map_error)?;
        Ok(None)
    }
    fn probe(&self) -> Result<(), MxcError> {
        self.inner()?.client.probe().map_err(map_error)
    }
    fn provision(&self, input: &PreparedProvision) -> Result<ProvisionOutput, MxcError> {
        let inner = self.inner()?;
        if let Some(ImageSource::Reference(reference)) = &input.spec.image {
            inner
                .backend
                .register_reference(reference, ImageDigest::Compute)
                .map_err(map_error)?;
        }
        inner
            .client
            .provision_with(&input.request, &input.spec)
            .map(|result| ProvisionOutput {
                sandbox_id: SandboxId(result.sandbox_id),
                metadata: result.metadata,
            })
            .map_err(map_error)
    }
    fn start(&self, sandbox_id: &SandboxId) -> Result<StartResult, MxcError> {
        self.inner()?.client.start(&sandbox_id.0).map_err(map_error)
    }
    fn diagnostics(&self, sandbox_id: &SandboxId) -> Result<SandboxDiagnostics, MxcError> {
        self.inner()?
            .backend
            .diagnostics(&sandbox_id.0)
            .map_err(map_error)
    }
    fn exec_and_wait(
        &self,
        sandbox_id: &SandboxId,
        request: &ExecRequest,
        cancellation: Option<&RunCancellation>,
        logger: &mut Logger,
    ) -> Result<ExecOutput, MxcError> {
        if let Some(cancellation) = cancellation {
            cancellation.check()?;
        }
        let inner = self.inner()?;
        inner.client.validate_exec(request).map_err(map_error)?;
        let captured = Arc::new(Mutex::new(Captured::default()));
        let io = ExecIo {
            stdout: Box::new(CaptureSink {
                shared: captured.clone(),
                stderr: false,
                limit: CAPTURE_LIMIT_BYTES,
            }),
            stderr: Box::new(CaptureSink {
                shared: captured.clone(),
                stderr: true,
                limit: CAPTURE_LIMIT_BYTES,
            }),
            stdin: None,
        };
        let control: Arc<dyn aci_edge_sandboxes::ExecControl> = Arc::from(
            inner
                .backend
                .exec(&sandbox_id.0, request, io)
                .map_err(map_error)?,
        );
        logger.log_diagnostic_line("NVX execution started");
        let deadline = request
            .process
            .timeout
            .filter(|v| !v.is_zero())
            .and_then(|v| {
                Instant::now()
                    .checked_add(v.saturating_add(Duration::from_millis(HOST_TIMEOUT_SLACK_MS)))
            });
        collect_execution(
            control,
            captured,
            deadline,
            cancellation,
            CAPTURE_LIMIT_BYTES,
        )
    }

    fn stop(&self, sandbox_id: &SandboxId) -> Result<(), MxcError> {
        self.inner()?
            .client
            .stop(&sandbox_id.0)
            .map(|_| ())
            .map_err(map_error)
    }
    fn deprovision(&self, sandbox_id: &SandboxId) -> Result<(), MxcError> {
        self.inner()?
            .client
            .deprovision(&sandbox_id.0)
            .map(|_| ())
            .map_err(map_error)
    }
    fn close(&mut self) -> Result<(), MxcError> {
        let Some(ClientInner {
            backend,
            client,
            _state_root_guard,
        }) = self.0.take()
        else {
            return Ok(());
        };
        drop(client);
        let backend = Arc::try_unwrap(backend).map_err(|_| {
            MxcError::backend_error("cannot close NVX agent: backend still has other owners")
        })?;
        backend.close().map_err(map_error)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use aci_edge_sandboxes::ExecControl;
    use std::sync::Condvar;

    #[test]
    fn runtime_discovery_prioritizes_explicit_over_registration() {
        let explicit = Path::new(r"C:\missing-explicit-nvx-bundle");
        let registered = Path::new(r"C:\missing-registered-nvx-bundle");
        let error = discover_bundle_from(Some(explicit), Some(registered), || {
            panic!("module lookup must not run")
        })
        .err()
        .unwrap();
        assert_eq!(error.code, MxcErrorCode::BackendUnavailable);
        assert!(error.message.contains("missing-explicit-nvx-bundle"));
        let error = discover_bundle_from(None, Some(registered), || {
            panic!("module lookup must not run")
        })
        .err()
        .unwrap();
        assert_eq!(error.code, MxcErrorCode::BackendUnavailable);
        assert!(error.message.contains("missing-registered-nvx-bundle"));
    }

    #[test]
    fn bundle_requires_each_runtime_file() {
        let directory = Path::new(r"C:\nvx-bundle");
        let files = std::cell::RefCell::new(Vec::new());
        assert!(selected_bundle_with(directory, &|path| {
            files.borrow_mut().push(path.to_path_buf());
            true
        })
        .is_ok());
        let files = files.into_inner();
        assert_eq!(files.len(), 147);
        for missing in &files {
            let error = selected_bundle_with(directory, &|path| path != missing)
                .err()
                .unwrap();
            assert_eq!(error.code, MxcErrorCode::BackendUnavailable);
            assert!(error
                .message
                .contains(&missing.to_string_lossy().to_string()));
        }
    }

    #[test]
    fn discovery_rejects_bundle_with_only_agent_library() {
        let directory = Path::new(r"C:\incomplete-nvx-bundle");
        let result = discover_bundle_from_with(
            Some(directory),
            None,
            || panic!("module lookup must not run"),
            &|_| panic!("module candidates must not be inspected"),
            &|_| panic!("module candidates must not be resolved"),
            &|path| path.ends_with("aci_edge_agent.dll"),
        );
        let error = result.err().unwrap();
        assert_eq!(error.code, MxcErrorCode::BackendUnavailable);
        assert!(error.message.contains("bundle-manifest.json"));
    }

    #[test]
    fn discovery_rejects_missing_kernel_config() {
        let directory = Path::new(r"C:\incomplete-nvx-bundle");
        let missing = directory.join(r"guest\vmlinux.config");
        let error = selected_bundle_with(directory, &|path| path != missing)
            .err()
            .unwrap();
        assert_eq!(error.code, MxcErrorCode::BackendUnavailable);
        assert!(error.message.contains("vmlinux.config"));
    }

    #[test]
    fn discovery_rejects_missing_source_manifest() {
        let directory = Path::new(r"C:\incomplete-nvx-bundle");
        let error =
            selected_bundle_with(directory, &|path| !path.ends_with("SOURCE-MANIFEST.json"))
                .err()
                .unwrap();
        assert_eq!(error.code, MxcErrorCode::BackendUnavailable);
        assert!(error.message.contains("SOURCE-MANIFEST.json"));
    }

    #[test]
    fn discovery_rejects_dangling_module_link_without_fallback() {
        let candidates_seen = std::cell::Cell::new(0);
        let result = discover_bundle_from_with(
            None,
            None,
            || Ok(PathBuf::from(r"C:\app\runtimes\win-x64\native\mxc_ffi.dll")),
            &|_| {
                candidates_seen.set(candidates_seen.get() + 1);
                Ok(true)
            },
            &|_| Err(MxcError::backend_unavailable("dangling module link")),
            &|_| panic!("invalid candidate must not be selected"),
        );
        let error = result.err().unwrap();
        assert_eq!(error.code, MxcErrorCode::BackendUnavailable);
        assert!(error.message.contains("dangling module link"));
        assert_eq!(candidates_seen.get(), 1);
    }

    #[test]
    fn discovery_accepts_valid_module_link() {
        let candidate = PathBuf::from(r"C:\app\runtimes\win-x64\native\aci-edge-sandboxes");
        let candidates_seen = std::cell::Cell::new(0);
        let bundle = discover_bundle_from_with(
            None,
            None,
            || Ok(PathBuf::from(r"C:\app\runtimes\win-x64\native\mxc_ffi.dll")),
            &|path| {
                candidates_seen.set(candidates_seen.get() + 1);
                assert_eq!(path, candidate);
                Ok(true)
            },
            &|path| {
                assert_eq!(path, candidate);
                Ok(())
            },
            &|_| true,
        )
        .unwrap();
        assert_eq!(bundle.directory(), candidate);
        assert_eq!(candidates_seen.get(), 1);
    }

    #[test]
    fn module_candidate_metadata_distinguishes_directory_file_and_absence() {
        let current = std::env::current_dir().unwrap();
        let file = std::env::current_exe().unwrap();
        assert!(module_candidate_exists(&current).unwrap());
        assert!(require_module_directory(&current).is_ok());
        assert!(module_candidate_exists(&file).unwrap());
        assert_eq!(
            require_module_directory(&file).unwrap_err().code,
            MxcErrorCode::BackendUnavailable
        );
        assert!(!module_candidate_exists(&current.join("missing-nvx-candidate-for-test")).unwrap());
    }

    #[test]
    fn module_candidates_cover_nuget_and_flat_layouts() {
        let module_dir = Path::new(r"C:\app\runtimes\win-x64\native");
        assert_eq!(
            module_candidates(module_dir),
            vec![
                PathBuf::from(r"C:\app\runtimes\win-x64\native\aci-edge-sandboxes"),
                PathBuf::from(r"C:\app\runtimes\win-x64\aci-edge-sandboxes"),
                PathBuf::from(r"C:\app\aci-edge-sandboxes"),
            ]
        );
        let mixed_module = Path::new(r"C:\app\Runtimes\Win-X64\Native\mxc_ffi.dll");
        let mixed_case = mixed_module.parent().unwrap();
        assert_eq!(
            module_candidates(mixed_case),
            vec![
                PathBuf::from(r"C:\app\Runtimes\Win-X64\Native\aci-edge-sandboxes"),
                PathBuf::from(r"C:\app\Runtimes\Win-X64\aci-edge-sandboxes"),
                PathBuf::from(r"C:\app\aci-edge-sandboxes"),
            ]
        );
        assert_eq!(
            module_candidates(Path::new(r"C:\app")),
            vec![PathBuf::from(r"C:\app\aci-edge-sandboxes")]
        );
    }

    #[test]
    fn runtime_directory_is_canonical_idempotent_and_rejects_conflicts() {
        let storage = OnceLock::new();
        let current = std::env::current_dir().unwrap();
        let parent = current.parent().unwrap();
        let path = current.to_str().unwrap();
        assert_eq!(
            register_directory_in(&storage, "relative")
                .unwrap_err()
                .code,
            MxcErrorCode::MalformedRequest
        );
        assert!(register_directory_in(&storage, path).is_ok());
        assert!(register_directory_in(&storage, current.join(".").to_str().unwrap()).is_ok());
        assert_eq!(
            register_directory_in(&storage, parent.to_str().unwrap())
                .unwrap_err()
                .code,
            MxcErrorCode::PolicyValidation
        );
        assert_eq!(
            register_directory_in(
                &OnceLock::new(),
                current.join("no-such-nvx-runtime").to_str().unwrap()
            )
            .unwrap_err()
            .code,
            MxcErrorCode::BackendUnavailable
        );
    }

    #[test]
    fn lifecycle_ids_preserve_native_tokens_and_reject_malformed_ids() {
        let token = "0123456789abcdef0123456789abcdef";
        let native = SandboxId::from_token(token).unwrap();
        let text = format!("microvm:{token}");
        assert_eq!(native.to_mxc_string(), text);
        assert_eq!(SandboxId::from_mxc(&text).unwrap(), native);
        for invalid in [
            "microvm:",
            "microvm:bad",
            "microvm:ABCDEF0123456789abcdef0123456789",
            "other:0123456789abcdef0123456789abcdef",
        ] {
            assert_eq!(
                SandboxId::from_mxc(invalid).unwrap_err().code,
                MxcErrorCode::MalformedId
            );
        }
    }

    #[test]
    fn streaming_queue_bounds_output_and_closing_releases_backpressure() {
        let (sender, receiver) = mpsc::sync_channel(1);
        let closed = Arc::new(AtomicBool::new(false));
        let mut sink = EventSink {
            sender,
            closed,
            stderr: true,
        };
        let closer = sink.close_handle().unwrap();
        let bytes = vec![0xff; 192 * 1024];
        let (done_sender, done_receiver) = mpsc::channel();
        let writer = std::thread::spawn(move || {
            let result = sink.write(&bytes);
            done_sender
                .send(result.map_err(|error| error.kind()))
                .unwrap();
        });
        match receiver.recv_timeout(Duration::from_secs(2)).unwrap() {
            Event::Stderr(data) => assert_eq!(data, vec![0xff; 64 * 1024]),
            _ => panic!("stderr must retain its stream and bytes"),
        }
        // Fill the single buffered slot, then ensure another write is interrupted.
        std::thread::sleep(Duration::from_millis(30));
        assert!(matches!(
            done_receiver.try_recv(),
            Err(mpsc::TryRecvError::Empty)
        ));
        closer.close();
        assert_eq!(
            done_receiver.recv_timeout(Duration::from_secs(2)).unwrap(),
            Err(io::ErrorKind::BrokenPipe)
        );
        writer.join().unwrap();
        // Closing does not discard already accepted output.
        match receiver.recv_timeout(Duration::from_secs(2)).unwrap() {
            Event::Stderr(data) => assert_eq!(data, vec![0xff; 64 * 1024]),
            _ => panic!("buffered bytes must remain readable"),
        }
    }

    #[test]
    fn streaming_cancel_returns_unknown_when_no_terminal_event_arrives() {
        let (sender, receiver) = mpsc::sync_channel(1);
        let execution = StreamingExecution(Arc::new(StreamingExecutionInner {
            control: Arc::new(FakeControl::new(false, ExecOutcome::Cancelled)),
            receiver: Mutex::new(Some(receiver)),
            closed: Arc::new(AtomicBool::new(false)),
            cancellation: Mutex::new(None),
        }));
        execution.cancel().unwrap();
        let error = execution.next(None, |_| ()).unwrap_err();
        assert_eq!(error.message, UNKNOWN_OUTCOME);
        execution.release().unwrap();
        drop(sender);
    }

    #[test]
    fn streaming_observer_delivers_binary_streams_before_the_exit_result() {
        let control = Arc::new(FakeControl::new(false, ExecOutcome::Exited(42)));
        let (sender, receiver) = mpsc::sync_channel(1);
        let closed = Arc::new(AtomicBool::new(false));
        let mut stdout = EventSink {
            sender: sender.clone(),
            closed: closed.clone(),
            stderr: false,
        };
        let mut stderr = EventSink {
            sender: sender.clone(),
            closed: closed.clone(),
            stderr: true,
        };
        let execution =
            StreamingExecution::observe(control.clone(), sender, receiver, closed).unwrap();
        let writer = std::thread::spawn(move || {
            let result = stdout
                .write(&vec![0xff; 128 * 1024])
                .and_then(|()| stderr.write(&vec![0x80; 128 * 1024]));
            *control.state.lock().unwrap() = true;
            control.wake.notify_all();
            result
        });
        let mut output = Vec::new();
        let mut error = Vec::new();
        loop {
            match execution
                .next(Some(5000), |event| event)
                .unwrap()
                .expect("stream progress")
            {
                Event::Stdout(bytes) => output.extend(bytes),
                Event::Stderr(bytes) => error.extend(bytes),
                Event::Exit(result) => {
                    assert_eq!(result.unwrap(), ExecOutcome::Exited(42));
                    break;
                }
            }
        }
        writer.join().unwrap().unwrap();
        assert_eq!(output, vec![0xff; 128 * 1024]);
        assert_eq!(error, vec![0x80; 128 * 1024]);
        execution.release().unwrap();
    }

    #[test]
    fn agent_setup_selects_host_cpu_profile_and_platform_snapshots_fit_its_defaults() {
        let bundle = BundledAgent::from_dir(r"C:\bundle").unwrap();
        let setup = agent_setup(&bundle, Path::new(r"C:\state"));
        assert_eq!(setup.cpu_profile, CpuProfile::Host);
        let json = serde_json::to_value(&setup).unwrap();
        assert_eq!(json["cpuProfile"], "host");
        assert!(json.get("platformSnapshots").is_none(), "{json}");

        let setup = setup.with_platform_snapshots(platform_snapshots());
        assert_eq!(
            serde_json::to_value(&setup).unwrap()["platformSnapshots"],
            serde_json::json!({"enabled": true, "maxVcpus": 1, "maxMemoryMib": 256})
        );
        // The templates must fit the sandboxes that keep the agent's default resources.
        setup.validate().unwrap();
        let defaults = setup.defaults.resources;
        assert_eq!(defaults.vcpus, Some(PLATFORM_SNAPSHOT_MAX_VCPUS));
        assert_eq!(defaults.memory_mib, Some(PLATFORM_SNAPSHOT_MAX_MEMORY_MIB));
    }

    #[test]
    fn state_root_is_keyed_by_bundle_owned_by_the_user_and_reused() {
        let local_app_data = tempfile::tempdir().unwrap();
        let root = state_root_in(local_app_data.path(), [0xab; 32]).unwrap();
        assert_eq!(
            root.path(),
            local_app_data
                .path()
                .join(r"Microsoft\MXC\nvx\abababababababab")
        );
        assert!(
            crate::mxc_common::filesystem_security::owner_is_current_user(root.path()).unwrap()
        );
        std::fs::write(root.path().join("registered-image"), b"cached").unwrap();
        let reused = state_root_in(local_app_data.path(), [0xab; 32]).unwrap();
        assert_eq!(reused.path(), root.path());
        assert_eq!(
            std::fs::read(reused.path().join("registered-image")).unwrap(),
            b"cached"
        );
        let other_bundle = state_root_in(local_app_data.path(), [0xcd; 32]).unwrap();
        assert_ne!(other_bundle.path(), root.path());
        assert!(!other_bundle.path().join("registered-image").exists());
    }

    struct FakeControl {
        state: Mutex<bool>,
        wake: Condvar,
        outcome: ExecOutcome,
    }

    impl FakeControl {
        fn new(complete: bool, outcome: ExecOutcome) -> Self {
            Self {
                state: Mutex::new(complete),
                wake: Condvar::new(),
                outcome,
            }
        }
    }

    impl ExecControl for FakeControl {
        fn wait(&self) -> aci_edge_sandboxes::Result<ExecOutcome> {
            let mut ready = self.state.lock().unwrap();
            while !*ready {
                ready = self.wake.wait(ready).unwrap();
            }
            Ok(self.outcome)
        }
        fn cancel(&self) -> aci_edge_sandboxes::Result<()> {
            *self.state.lock().unwrap() = true;
            self.wake.notify_all();
            Ok(())
        }
    }

    #[test]
    fn capture_enforces_one_combined_binary_limit() {
        for (stderr, overflow) in [(b"xy".as_slice(), false), (b"xyz".as_slice(), true)] {
            let capture = Arc::new(Mutex::new(Captured::default()));
            let mut stdout = CaptureSink {
                shared: capture.clone(),
                stderr: false,
                limit: 5,
            };
            let mut error = CaptureSink {
                shared: capture.clone(),
                stderr: true,
                limit: 5,
            };
            stdout.write(&[0xff, 0, 0x80]).unwrap();
            assert_eq!(error.write(stderr).is_err(), overflow);
            let control = Arc::new(FakeControl::new(!overflow, ExecOutcome::Exited(7)));
            let result = collect_execution(control, capture, None, None, 5);
            if overflow {
                assert!(result.unwrap_err().message.contains("capture limit of 5"));
            } else {
                let output = result.unwrap();
                assert_eq!(output.outcome, ExecOutcome::Exited(7));
                assert_eq!(output.stdout, [0xff, 0, 0x80]);
                assert_eq!(output.stderr, stderr);
            }
        }
    }

    #[test]
    fn unbounded_output_without_a_deadline_hits_the_capture_limit() {
        let captured = Arc::new(Mutex::new(Captured::default()));
        let mut sink = CaptureSink {
            shared: captured.clone(),
            stderr: false,
            limit: 16,
        };
        let writer = std::thread::spawn(move || while sink.write(&[0xff]).is_ok() {});
        let control = Arc::new(FakeControl::new(false, ExecOutcome::Cancelled));
        let error = collect_execution(control.clone(), captured, None, None, 16).unwrap_err();
        writer.join().unwrap();
        assert!(error.message.contains("capture limit of 16"));
        assert!(*control.state.lock().unwrap());
    }

    #[test]
    fn cancellation_and_host_deadline_wait_for_terminal_outcome() {
        let cancelled = RunCancellation::default();
        cancelled.request();
        let control = Arc::new(FakeControl::new(false, ExecOutcome::Cancelled));
        let error = collect_execution(
            control.clone(),
            Arc::new(Mutex::new(Captured::default())),
            None,
            Some(&cancelled),
            5,
        )
        .unwrap_err();
        assert_eq!(error.message, "execution cancelled");
        assert!(*control.state.lock().unwrap());

        let captured = Arc::new(Mutex::new(Captured {
            stdout: b"partial".to_vec(),
            ..Default::default()
        }));
        let control = Arc::new(FakeControl::new(false, ExecOutcome::Cancelled));
        let output =
            collect_execution(control.clone(), captured, Some(Instant::now()), None, 32).unwrap();
        assert_eq!(output.outcome, ExecOutcome::TimedOut);
        assert_eq!(output.stdout, b"partial");
        assert!(*control.state.lock().unwrap());
    }

    #[test]
    fn failed_cancel_waits_for_independent_observer_error() {
        struct FailedCancel {
            done: Mutex<bool>,
            wake: Condvar,
            cancelled: mpsc::Sender<()>,
        }
        impl ExecControl for FailedCancel {
            fn wait(&self) -> aci_edge_sandboxes::Result<ExecOutcome> {
                let mut done = self.done.lock().unwrap();
                while !*done {
                    done = self.wake.wait(done).unwrap();
                }
                Err(Error::new(
                    ErrorCode::BackendError,
                    "workload may still be running; stop or deprovision the sandbox",
                )
                .with_source("native cancellation failed"))
            }
            fn cancel(&self) -> aci_edge_sandboxes::Result<()> {
                self.cancelled.send(()).unwrap();
                Err(Error::new(ErrorCode::BackendError, "cancel failed"))
            }
        }
        let (sender, receiver) = mpsc::channel();
        let control = Arc::new(FailedCancel {
            done: Mutex::new(false),
            wake: Condvar::new(),
            cancelled: sender,
        });
        let observer_control = control.clone();
        let observer = std::thread::spawn(move || {
            let cancelled = receiver.recv_timeout(Duration::from_secs(5)).is_ok();
            std::thread::sleep(Duration::from_millis(100));
            *observer_control.done.lock().unwrap() = true;
            observer_control.wake.notify_all();
            cancelled
        });
        let cancelled = RunCancellation::default();
        cancelled.request();
        let error = collect_execution(
            control,
            Arc::new(Mutex::new(Captured::default())),
            None,
            Some(&cancelled),
            5,
        )
        .unwrap_err();
        assert!(observer.join().unwrap(), "cancellation was never requested");
        assert!(error.message.contains("execution cancelled"), "{error}");
        assert!(error.message.contains("cancel failed"), "{error}");
        assert!(
            error.message.contains("workload may still be running"),
            "{error}"
        );
        assert!(
            error.message.contains("native cancellation failed"),
            "{error}"
        );
    }

    #[test]
    fn cancellation_is_bounded_even_without_an_outcome_or_cancel_return() {
        use std::sync::atomic::{AtomicBool, Ordering};

        #[derive(Clone, Copy)]
        enum Cancel {
            Accept,
            Fail,
            Block,
            BlockWithOutcome,
        }
        struct StalledControl {
            release: Mutex<bool>,
            wake: Condvar,
            attempted: AtomicBool,
            cancel: Cancel,
        }
        impl StalledControl {
            fn wait_for_release(&self) {
                let mut release = self.release.lock().unwrap();
                while !*release {
                    release = self.wake.wait(release).unwrap();
                }
            }
        }
        impl ExecControl for StalledControl {
            fn wait(&self) -> aci_edge_sandboxes::Result<ExecOutcome> {
                if matches!(self.cancel, Cancel::BlockWithOutcome) {
                    let mut release = self.release.lock().unwrap();
                    while !self.attempted.load(Ordering::Acquire) {
                        release = self.wake.wait(release).unwrap();
                    }
                    return Ok(ExecOutcome::Exited(7));
                }
                self.wait_for_release();
                Ok(ExecOutcome::Cancelled)
            }
            fn cancel(&self) -> aci_edge_sandboxes::Result<()> {
                {
                    let _release = self.release.lock().unwrap();
                    self.attempted.store(true, Ordering::Release);
                    self.wake.notify_all();
                }
                match self.cancel {
                    Cancel::Accept => Ok(()),
                    Cancel::Fail => Err(Error::new(ErrorCode::BackendError, "cancel failed")),
                    Cancel::Block | Cancel::BlockWithOutcome => {
                        self.wait_for_release();
                        Ok(())
                    }
                }
            }
        }

        for cancel in [
            Cancel::Accept,
            Cancel::Fail,
            Cancel::Block,
            Cancel::BlockWithOutcome,
        ] {
            let control = Arc::new(StalledControl {
                release: Mutex::new(false),
                wake: Condvar::new(),
                attempted: AtomicBool::new(false),
                cancel,
            });
            let worker_control = control.clone();
            let (sender, receiver) = mpsc::channel();
            let caller = std::thread::spawn(move || {
                let cancellation = RunCancellation::default();
                if matches!(cancel, Cancel::Accept | Cancel::BlockWithOutcome) {
                    cancellation.request();
                }
                let captured = Captured {
                    overflow: matches!(cancel, Cancel::Block),
                    ..Default::default()
                };
                let result = collect_execution(
                    worker_control,
                    Arc::new(Mutex::new(captured)),
                    matches!(cancel, Cancel::Fail).then(Instant::now),
                    Some(&cancellation),
                    5,
                );
                let _ = sender.send(result);
            });
            let result = receiver.recv_timeout(Duration::from_secs(4));
            let attempted = control.attempted.load(Ordering::Acquire);
            // Release fake native calls even when the bounded-return assertion fails.
            *control.release.lock().unwrap() = true;
            control.wake.notify_all();
            caller.join().unwrap();
            assert!(attempted, "the cancellation path was not reached");
            let error = result
                .expect("cancellation must return before the independent watchdog")
                .unwrap_err();
            assert_eq!(error.code, MxcErrorCode::BackendError);
            if matches!(cancel, Cancel::BlockWithOutcome) {
                assert!(error.message.starts_with(CANCEL_UNFINISHED), "{error}");
                assert!(!error.message.contains("outcome is unknown"), "{error}");
            } else {
                assert!(error.message.starts_with(UNKNOWN_OUTCOME), "{error}");
            }
            let primary = match cancel {
                Cancel::Accept | Cancel::BlockWithOutcome => "execution cancelled",
                Cancel::Fail => "cancel failed",
                Cancel::Block => "capture limit of 5",
            };
            assert!(error.message.contains(primary), "{error}");
        }
    }

    #[test]
    fn release_failure_keeps_outcome_and_native_cause() {
        struct ReleaseFailure;
        impl ExecControl for ReleaseFailure {
            fn wait(&self) -> aci_edge_sandboxes::Result<ExecOutcome> {
                Err(Error::new(
                    ErrorCode::BackendError,
                    "execution exited but release failed",
                )
                .with_source("native release failure"))
            }
            fn cancel(&self) -> aci_edge_sandboxes::Result<()> {
                panic!("completed execution must not be cancelled")
            }
        }
        let error = collect_execution(
            Arc::new(ReleaseFailure),
            Arc::new(Mutex::new(Captured::default())),
            None,
            None,
            5,
        )
        .unwrap_err();
        assert_eq!(error.code, MxcErrorCode::BackendError);
        assert!(error
            .message
            .contains("execution exited but release failed"));
        assert!(error.message.contains("native release failure"));
    }

    #[test]
    fn cancellation_and_wait_errors_are_reported() {
        struct FailingControl {
            state: Mutex<bool>,
            wake: Condvar,
        }
        impl ExecControl for FailingControl {
            fn wait(&self) -> aci_edge_sandboxes::Result<ExecOutcome> {
                let mut ready = self.state.lock().unwrap();
                while !*ready {
                    ready = self.wake.wait(ready).unwrap();
                }
                Err(Error::new(ErrorCode::BackendError, "wait failed"))
            }
            fn cancel(&self) -> aci_edge_sandboxes::Result<()> {
                *self.state.lock().unwrap() = true;
                self.wake.notify_all();
                Err(Error::new(ErrorCode::BackendError, "cancel failed"))
            }
        }
        let cancelled = RunCancellation::default();
        cancelled.request();
        let control = Arc::new(FailingControl {
            state: Mutex::new(false),
            wake: Condvar::new(),
        });
        let error = collect_execution(
            control,
            Arc::new(Mutex::new(Captured::default())),
            None,
            Some(&cancelled),
            5,
        )
        .unwrap_err();
        assert_eq!(error.code, MxcErrorCode::BackendError);
        assert!(error.message.contains("execution cancelled"));
        assert!(error.message.contains("cancel failed"));
        assert!(error.message.contains("wait failed"));
    }

    #[test]
    fn maps_crate_errors_without_success_fallbacks() {
        for (native, expected) in [
            (ErrorCode::MalformedRequest, MxcErrorCode::MalformedRequest),
            (ErrorCode::PolicyValidation, MxcErrorCode::PolicyValidation),
            (
                ErrorCode::BackendUnavailable,
                MxcErrorCode::BackendUnavailable,
            ),
            (ErrorCode::Unsupported, MxcErrorCode::BackendError),
        ] {
            assert_eq!(map_error(Error::new(native, "detail")).code, expected);
        }
    }
}