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

//! `mxc_engine` — the MXC execution engine.
//!
//! This crate owns the logic that turns an execution request into a running
//! sandbox: backend dispatch, host-platform probing, and execution of requests
//! already normalized by either the public Rust SDK (`mxc-sdk`) or the JSON
//! parser. It is the single implementation that both the public Rust SDK and
//! the executor binaries call into, so backend selection lives in exactly one
//! place.
//!
//! It depends on the `backends/*` crates (cfg-split by target), which is why
//! it cannot live in `mxc_common` (the cross-platform foundation those backends
//! build on).
//!
//! ## Surface
//!
//! - [`spawn_execution_request`] — spawn a streaming [`SandboxProcess`] handle
//!   for a normalized [`ExecutionRequest`].
//! - [`spawn_one_shot_json`] — parse and spawn a raw exact-version one-shot
//!   JSON request.
//! - [`run`] / [`resolve_runner`] (Windows) — run-to-completion backend
//!   selection and execution.
//! - [`run_state_aware`] — state-aware lifecycle backend resolution + dispatch.
//! - [`platform_support`] / [`PlatformSupport`] — host support detection.
//! - [`available_backends`] / [`AvailableBackend`] — read-only host
//!   backend-availability probe (with effective isolation tier).
//! - [`Error`] / [`ErrorCode`] — the crate-owned error facade over
//!   `mxc_common`'s internal error type.

mod backend_registry;
mod dispatch;
mod error;
mod experimental;
#[cfg(target_os = "windows")]
mod guarded_capture;
mod platform;
mod probe;
#[cfg(target_os = "windows")]
mod request_probe;
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
mod run;
mod state_aware;
#[cfg(target_os = "windows")]
mod verbose_telemetry;

pub use error::{Error, ErrorCode};
#[cfg(all(target_os = "windows", feature = "isolation_session"))]
pub use platform::isolation_session_available;
pub use platform::{platform_support, BubblewrapNetworkSupport, PlatformSupport, ProxyEnforcement};
pub use probe::{available_backends, to_json_pretty, AvailableBackend, BackendCapability};
#[cfg(target_os = "windows")]
pub use request_probe::{probe_execution_request, ProbeFacts, ProbeOutput, UiCapabilitySupport};
#[cfg(target_os = "windows")]
pub fn guarded_capture_available() -> bool {
    guarded_capture::is_available()
}
#[cfg(target_os = "windows")]
pub use run::resolve_runner_for_audit;
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub use run::{log_policy_hash, resolve_runner, run, ResolvedRunner};
pub use state_aware::{
    exec_state_aware_attached, exec_state_aware_json, exec_state_aware_pty_json,
    exec_typed_state_aware_attached_request, exec_typed_state_aware_pty_request,
    exec_typed_state_aware_request, run_state_aware, run_state_aware_json,
    run_typed_state_aware_request, EngineProvisionMetadata, EngineStateAwareResult,
};
#[cfg(target_os = "windows")]
pub use verbose_telemetry::emit_verbose_telemetry;

use crate::mxc_common::logger::{Logger, Mode};
use crate::mxc_common::models::{
    ContainmentBackend, ExecutionRequest, FailurePhase, ScriptResponse,
};
use crate::mxc_common::mxc_error::MxcError;
use crate::mxc_common::sandbox_process::{
    NativeStdio, PtyReaderWithCloser, PtySize, SandboxProcess, StreamCloser,
};
use crate::mxc_common::state_aware_request::MxcRequest;
use crate::mxc_common::telemetry;

/// Spawn a streaming [`SandboxProcess`] handle for a normalized
/// [`ExecutionRequest`].
///
/// Selects the containment backend for the host, spawns the sandboxed process
/// with piped stdio, and returns the handle. No pty is allocated. Backends
/// without a streaming implementation return an [`Error`] with
/// [`ErrorCode::UnsupportedContainment`].
///
/// # Safety / lifetime contract for library-context callers
///
/// When this crate is compiled into a dynamically-loadable library (the
/// `mxc_ffi` cdylib, or a host that dlopens `mxc-sdk`), the ETW telemetry
/// provider is registered while an invocation is live. The provider retains
/// callbacks into this module's code, so **the library must remain loaded
/// until every spawned handle produced by this function has been dropped**
/// (which releases the corresponding provider reference through
/// [`telemetry::shutdown`] via the internal `TelemetryProcess` `Drop` impl below).
/// Callers that dlclose / `FreeLibrary` while a spawned handle is still live
/// would leave ETW with dangling callbacks into unmapped memory.
///
/// The registration is reference-counted per `telemetry::init` call and
/// released once when the returned handle is dropped, so multiple concurrent
/// spawns from the same load are safe as long as the library outlives them.
pub fn spawn_execution_request(
    request: &ExecutionRequest,
) -> Result<Box<dyn SandboxProcess>, Error> {
    spawn_execution_request_with_logger(request, Logger::new(Mode::Buffer))
}

/// Spawn a raw exact-version one-shot JSON request as a streaming process.
///
/// `experimental` is the caller's runtime opt-in. It is a parameter rather than
/// a JSON field so that a configuration cannot grant itself experimental access.
/// The same library-lifetime contract as [`spawn_execution_request`] applies.
pub fn spawn_one_shot_json(
    request_json: &str,
    experimental: bool,
) -> Result<Box<dyn SandboxProcess>, Error> {
    let mut logger = Logger::new(Mode::Buffer);
    let request = parse_one_shot_json(request_json, experimental, &mut logger)?;
    spawn_execution_request_with_logger(&request, logger)
}

fn parse_one_shot_json(
    request_json: &str,
    experimental: bool,
    logger: &mut Logger,
) -> Result<ExecutionRequest, Error> {
    let mut request = match crate::mxc_common::config_parser::load_mxc_request_from_json(
        request_json,
        logger,
    )
    .map_err(state_aware::parse_error_to_mxc)
    .map_err(Error::from)?
    {
        MxcRequest::OneShot(request) => request,
        MxcRequest::StateAware(_) => {
            return Err(Error::from(MxcError::malformed_request(
                "expected a one-shot request; lifecycle requests use the state-aware JSON entry points",
            )));
        }
    };
    request.experimental_enabled = experimental;
    Ok(request)
}

fn spawn_execution_request_with_logger(
    request: &ExecutionRequest,
    logger: Logger,
) -> Result<Box<dyn SandboxProcess>, Error> {
    spawn_execution_request_with_logger_and(request, logger, dispatch::spawn_runner)
}

fn spawn_execution_request_with_logger_and(
    request: &ExecutionRequest,
    mut logger: Logger,
    spawn: impl FnOnce(&ExecutionRequest, &mut Logger) -> Result<Box<dyn SandboxProcess>, MxcError>,
) -> Result<Box<dyn SandboxProcess>, Error> {
    let telemetry_active = request
        .telemetry
        .as_ref()
        .map(|config| telemetry::init(config, &mut logger))
        .unwrap_or(false);
    let mut telemetry_registration = TelemetryRegistration::new(telemetry_active);
    let requested_sandbox_kind = request
        .telemetry
        .as_ref()
        .and_then(|config| config.requested_sandbox_kind);
    let containment = request.containment.clone();
    let started = std::time::Instant::now();
    let process = match spawn(request, &mut logger) {
        Ok(process) => process,
        Err(error) => {
            // Preserve the actual error category so bounded telemetry
            // categorises malformed requests, unsupported containment, and
            // policy validation failures under their real reason — not the
            // catch-all `InitError`. Shares the exhaustive `MxcErrorCode` →
            // `FailureReason` mapping with the state-aware path.
            telemetry::emit_sdk_early_exit_with_kind(
                telemetry_registration.transfer(),
                &containment,
                requested_sandbox_kind,
                telemetry::classify_mxc_error(&error),
            );
            return Err(Error::from(error));
        }
    };
    let extra_warnings = logger.take_warnings();
    let process: Box<dyn SandboxProcess> = ProcessWithWarnings::wrap(process, extra_warnings);
    if telemetry_registration.active() {
        Ok(Box::new(TelemetryProcess::new(
            process,
            telemetry_registration.transfer(),
            TelemetryMode::OneShot {
                containment,
                requested_sandbox_kind,
            },
            started,
        )))
    } else {
        Ok(process)
    }
}

/// Spawn a sandbox attached to an MXC-owned pseudo-terminal.
pub fn spawn_with_pty(
    request: &ExecutionRequest,
    size: crate::mxc_common::sandbox_process::PtySize,
) -> Result<Box<dyn SandboxProcess>, Error> {
    spawn_execution_request_with_logger_and(
        request,
        Logger::new(Mode::Buffer),
        |request, logger| dispatch::spawn_pty_runner(request, logger, size),
    )
}

/// Spawn a raw exact-version one-shot JSON request attached to an MXC-owned PTY.
pub fn spawn_one_shot_pty_json(
    request_json: &str,
    experimental: bool,
    size: crate::mxc_common::sandbox_process::PtySize,
) -> Result<Box<dyn SandboxProcess>, Error> {
    let mut logger = Logger::new(Mode::Buffer);
    let request = parse_one_shot_json(request_json, experimental, &mut logger)?;
    spawn_execution_request_with_logger_and(&request, logger, |request, logger| {
        dispatch::spawn_pty_runner(request, logger, size)
    })
}

pub(crate) struct TelemetryRegistration {
    active: bool,
}

impl TelemetryRegistration {
    pub(crate) fn new(active: bool) -> Self {
        Self { active }
    }

    pub(crate) fn active(&self) -> bool {
        self.active
    }

    pub(crate) fn transfer(&mut self) -> bool {
        std::mem::take(&mut self.active)
    }
}

impl Drop for TelemetryRegistration {
    fn drop(&mut self) {
        if self.active {
            telemetry::shutdown();
        }
    }
}

/// Streaming process wrapper that owns one telemetry provider reference and
/// emits exactly one terminal event for this SDK invocation.
///
/// # Terminal-event invariant
///
/// Every non-nop path a caller can drive this wrapper through emits exactly
/// one terminal telemetry event before the provider reference is released:
///
/// * [`SandboxProcess::wait`] — real completion / timeout / spawn error.
/// * [`SandboxProcess::try_wait`] — emits when a poll observes an exit or a
///   terminal timeout. A pending or otherwise failed poll leaves the invariant
///   to a later successful `try_wait`, `wait`, `kill`, or `Drop`.
/// * [`SandboxProcess::kill`] — cancellation event after the wrapped process
///   confirms the kill succeeded. A failed kill leaves the slot active for a
///   later `wait` / successful `try_wait`.
/// * [`Drop`] — polls once for a completed child and emits its real exit code;
///   only a still-running or unpollable child is reported as abandoned.
///
/// `active` doubles as the exactly-once flag: it starts `true`, and every
/// terminal path calls [`TelemetryProcess::emit`] which flips it to `false`
/// after the event and after [`telemetry::shutdown`] releases the provider
/// reference.
struct TelemetryProcess {
    inner: Box<dyn SandboxProcess>,
    active: bool,
    // Set by kill_for_timeout() so telemetry reports a timeout instead of a
    // normal exit or cancellation. The backend keeps its own timeout state so
    // later wait() and try_wait() calls also report the timeout.
    timeout_requested: bool,
    warnings: Vec<String>,
    mode: TelemetryMode,
    started: std::time::Instant,
}

enum TelemetryMode {
    OneShot {
        containment: ContainmentBackend,
        requested_sandbox_kind: Option<&'static str>,
    },
    StateAware {
        backend: String,
        phase: String,
        correlation_vector: String,
        requested_sandbox_kind: Option<&'static str>,
    },
}

pub(crate) fn wrap_state_aware_telemetry_process_with_kind(
    process: Box<dyn SandboxProcess>,
    active: bool,
    backend: String,
    phase: String,
    correlation_vector: String,
    requested_sandbox_kind: Option<&'static str>,
    started: std::time::Instant,
) -> Box<dyn SandboxProcess> {
    if active {
        Box::new(TelemetryProcess::new(
            process,
            true,
            TelemetryMode::StateAware {
                backend,
                phase,
                correlation_vector,
                requested_sandbox_kind,
            },
            started,
        ))
    } else {
        process
    }
}

impl TelemetryProcess {
    fn new(
        inner: Box<dyn SandboxProcess>,
        active: bool,
        mode: TelemetryMode,
        started: std::time::Instant,
    ) -> Self {
        let warnings = inner.warnings().to_vec();
        Self {
            inner,
            active,
            timeout_requested: false,
            warnings,
            mode,
            started,
        }
    }

    fn completion_response(
        &self,
        result: &std::io::Result<i32>,
        include_output_metadata: bool,
    ) -> ScriptResponse {
        let output_metadata = include_output_metadata
            .then(|| self.inner.output_metadata().cloned().map(Box::new))
            .flatten();
        let mut response = match result {
            Ok(exit_code) => ScriptResponse {
                exit_code: *exit_code,
                ..Default::default()
            },
            Err(error) if error.kind() == std::io::ErrorKind::TimedOut => ScriptResponse {
                error_message: "sandbox execution timed out".to_string(),
                failure_phase: FailurePhase::Timeout,
                ..Default::default()
            },
            Err(error) => ScriptResponse {
                error_message: error.to_string(),
                failure_phase: FailurePhase::PostLaunchFailed,
                ..Default::default()
            },
        };
        response.output_metadata = output_metadata;
        response
    }

    fn report_verbose_telemetry_failure(&mut self, error: String) {
        let warning =
            format!("telemetry: captureDenials verbose artifact was not emitted: {error}");
        if !self.warnings.contains(&warning) {
            self.warnings.push(warning);
        }
    }

    /// Emit the single terminal event for this invocation and release the
    /// provider reference. Idempotent — subsequent calls (from another exit
    /// path or `Drop`) are silent no-ops.
    fn emit(&mut self, result: &std::io::Result<i32>) {
        self.emit_inner(result, true);
    }

    /// Emit completion after a nonblocking terminal poll without forcing
    /// backend teardown to finalize capture metadata.
    fn emit_after_poll(&mut self, result: &std::io::Result<i32>) {
        self.emit_inner(result, false);
    }

    fn emit_inner(&mut self, result: &std::io::Result<i32>, include_verbose: bool) {
        if !self.active {
            return;
        }
        let response = self.completion_response(result, include_verbose);
        let verbose_error = match &self.mode {
            TelemetryMode::OneShot {
                containment,
                requested_sandbox_kind,
            } => {
                #[cfg(target_os = "windows")]
                let verbose_error = include_verbose
                    .then(|| {
                        emit_verbose_telemetry(
                            true,
                            containment,
                            *requested_sandbox_kind,
                            &response,
                        )
                        .err()
                    })
                    .flatten();
                #[cfg(not(target_os = "windows"))]
                let verbose_error: Option<String> = None;
                telemetry::emit_sdk_completion_with_kind(
                    true,
                    containment,
                    *requested_sandbox_kind,
                    &response,
                    self.started.elapsed(),
                );
                verbose_error
            }
            TelemetryMode::StateAware {
                backend,
                phase,
                correlation_vector,
                requested_sandbox_kind,
            } => {
                let outcome = match result {
                    Ok(exit_code) => Ok(
                        crate::mxc_common::state_aware_dispatch::DispatchOutcome::ExecCompleted {
                            exit_code: *exit_code,
                        },
                    ),
                    Err(error) => Err(crate::mxc_common::mxc_error::MxcError::backend_error(
                        error.to_string(),
                    )),
                };
                let failure_reason = Self::state_aware_wait_failure_reason(result);
                telemetry::emit_sdk_state_aware_with_kind_and_failure(
                    true,
                    *requested_sandbox_kind,
                    telemetry::TelemetryContext {
                        backend,
                        phase,
                        correlation_vector,
                    },
                    &outcome,
                    self.started.elapsed(),
                    failure_reason,
                );
                None
            }
        };
        if let Some(error) = verbose_error {
            self.report_verbose_telemetry_failure(error);
        }
        self.active = false;
    }

    fn state_aware_wait_failure_reason(
        result: &std::io::Result<i32>,
    ) -> Option<telemetry::FailureReason> {
        result
            .as_ref()
            .err()
            .filter(|error| error.kind() == std::io::ErrorKind::TimedOut)
            .map(|_| telemetry::FailureReason::Timeout)
    }

    /// Emit a synthesised terminal event when no real completion result is
    /// available (drop-without-wait). Routes through
    /// [`Self::emit`] so it shares the exactly-once slot and the
    /// provider-release path with the natural exit paths.
    fn emit_synthetic(&mut self, kind: SyntheticTerminal) {
        if !self.active {
            return;
        }
        let (raw_kind, message) = match kind {
            SyntheticTerminal::Dropped => (
                std::io::ErrorKind::Other,
                "sandbox handle was dropped before completion",
            ),
        };
        // The Err path in `emit` classifies non-timeout errors as
        // PostLaunchFailed → FailureReason::InitError (one-shot) or
        // BackendError → FailureReason::ProcessError (state-aware).
        self.emit(&Err(std::io::Error::new(raw_kind, message)));
    }

    /// Emit the terminal event for a confirmed explicit kill.
    fn emit_cancellation(&mut self) {
        if !self.active {
            return;
        }
        match &self.mode {
            TelemetryMode::OneShot {
                containment,
                requested_sandbox_kind,
            } => telemetry::emit_sdk_cancellation_with_kind(
                true,
                *requested_sandbox_kind,
                telemetry::TelemetryContext {
                    backend: containment.wire_name(),
                    phase: "",
                    correlation_vector: "",
                },
                self.started.elapsed(),
            ),
            TelemetryMode::StateAware {
                backend,
                phase,
                correlation_vector,
                requested_sandbox_kind,
            } => telemetry::emit_sdk_cancellation_with_kind(
                true,
                *requested_sandbox_kind,
                telemetry::TelemetryContext {
                    backend,
                    phase,
                    correlation_vector,
                },
                self.started.elapsed(),
            ),
        }
        self.active = false;
    }
}

/// Synthetic terminal callsites for which no real completion result is
/// available, so [`TelemetryProcess::emit_synthetic`]
/// can attribute the event to the exit path that produced it.
#[derive(Debug, Clone, Copy)]
enum SyntheticTerminal {
    /// The wrapper was dropped without a preceding `wait` / successful `try_wait`.
    Dropped,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DropDisposition {
    Exited(i32),
    TimedOut,
    Abandoned,
}

fn observe_before_drop(process: &mut dyn SandboxProcess) -> DropDisposition {
    match process.try_wait() {
        Ok(Some(exit_code)) => DropDisposition::Exited(exit_code),
        Err(error) if error.kind() == std::io::ErrorKind::TimedOut => DropDisposition::TimedOut,
        Ok(None) | Err(_) => DropDisposition::Abandoned,
    }
}

impl Drop for TelemetryProcess {
    fn drop(&mut self) {
        // If `wait` / `try_wait(Ok(Some))` / `kill` already emitted the
        // terminal event, `active` is false and this is a no-op. Otherwise,
        // preserve a completion that raced with Drop instead of misreporting a
        // successful fire-and-forget run as abandonment.
        if !self.active {
            return;
        }
        match observe_before_drop(self.inner.as_mut()) {
            DropDisposition::Exited(exit_code) => {
                // Finalize backend-owned output metadata after the nonblocking
                // observation, while preserving the already-observed exit code.
                let _ = self.inner.wait();
                self.emit(&Ok(exit_code));
            }
            DropDisposition::TimedOut => self.emit(&Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "sandbox execution timed out",
            ))),
            DropDisposition::Abandoned => self.emit_synthetic(SyntheticTerminal::Dropped),
        }
    }
}

impl SandboxProcess for TelemetryProcess {
    /// Merged at the call rather than when this wrapper was built: the wrapped
    /// process can report a cleanup failure long after that.
    fn warnings(&self) -> Vec<String> {
        let mut merged = self.inner.warnings();
        for warning in &self.warnings {
            if !merged.contains(warning) {
                merged.push(warning.clone());
            }
        }
        merged
    }

    fn output_metadata(&self) -> Option<&crate::mxc_common::models::SandboxOutputMetadata> {
        self.inner.output_metadata()
    }

    fn take_stdin(&mut self) -> Option<Box<dyn std::io::Write + Send>> {
        self.inner.take_stdin()
    }

    fn stdin_closer(&self) -> Option<Box<dyn StreamCloser>> {
        self.inner.stdin_closer()
    }

    fn take_native_stdio(&mut self) -> std::io::Result<Option<NativeStdio>> {
        self.inner.take_native_stdio()
    }

    fn is_pty(&self) -> bool {
        self.inner.is_pty()
    }

    fn pty_clone_reader(&self) -> std::io::Result<Box<dyn std::io::Read + Send>> {
        self.inner.pty_clone_reader()
    }

    fn pty_clone_reader_with_closer(&self) -> std::io::Result<PtyReaderWithCloser> {
        self.inner.pty_clone_reader_with_closer()
    }

    fn pty_take_writer(&self) -> std::io::Result<Box<dyn std::io::Write + Send>> {
        self.inner.pty_take_writer()
    }

    fn pty_resize(&self, size: PtySize) -> std::io::Result<()> {
        self.inner.pty_resize(size)
    }

    fn pty_size(&self) -> std::io::Result<PtySize> {
        self.inner.pty_size()
    }

    fn take_stdout(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
        self.inner.take_stdout()
    }

    fn take_stderr(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
        self.inner.take_stderr()
    }

    fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
        let result = match self.inner.try_wait() {
            Ok(Some(_)) if self.timeout_requested => Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "sandbox execution timed out",
            )),
            result => result,
        };
        match &result {
            // Preserve the nonblocking contract. Capture metadata is finalized
            // only by backend teardown, so this path emits completion without
            // attempting the optional verbose artifact.
            Ok(Some(exit_code)) => {
                self.emit_after_poll(&Ok(*exit_code));
            }
            // Still running: leave the invariant to a later `wait` / `kill` / `Drop`.
            Ok(None) => {}
            // Backends use TimedOut only for a settled terminal timeout.
            Err(error) if error.kind() == std::io::ErrorKind::TimedOut => {
                self.emit(&Err(std::io::Error::new(error.kind(), error.to_string())));
            }
            // A poll error does not prove termination. Preserve the slot and
            // provider so a later wait, successful poll, kill, or Drop can
            // report the actual terminal outcome.
            Err(_) => {}
        }
        result
    }

    fn id(&self) -> u32 {
        self.inner.id()
    }

    fn kill(&mut self) -> std::io::Result<()> {
        // A failed kill does not prove termination, so retain the exactly-once
        // slot for a later wait/try_wait that can report the real outcome.
        let result = self.inner.kill();
        if result.is_ok() {
            self.emit_cancellation();
        }
        result
    }

    fn kill_for_timeout(&mut self) -> std::io::Result<()> {
        self.timeout_requested = true;
        let result = self.inner.kill_for_timeout();
        if result.is_ok() {
            self.emit(&Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "sandbox execution timed out",
            )));
        }
        result
    }

    fn wait(&mut self) -> std::io::Result<i32> {
        let result = match self.inner.wait() {
            Ok(_) if self.timeout_requested => Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "sandbox execution timed out",
            )),
            result => result,
        };
        self.emit(&result);
        result
    }

    fn stdout_closer(&self) -> Option<Box<dyn StreamCloser>> {
        self.inner.stdout_closer()
    }

    fn stderr_closer(&self) -> Option<Box<dyn StreamCloser>> {
        self.inner.stderr_closer()
    }
}

/// A streaming process paired with warnings emitted during spawn.
pub(crate) struct ProcessWithWarnings {
    inner: Box<dyn SandboxProcess>,
    warnings: Vec<String>,
}

impl ProcessWithWarnings {
    /// Wrap `inner` so its `warnings()` reports the union of its own warnings
    /// and `extra_warnings` (duplicates deduplicated). Returns `inner`
    /// unchanged when `extra_warnings` is empty.
    pub(crate) fn wrap(
        inner: Box<dyn SandboxProcess>,
        extra_warnings: Vec<String>,
    ) -> Box<dyn SandboxProcess> {
        if extra_warnings.is_empty() {
            inner
        } else {
            Box::new(ProcessWithWarnings {
                inner,
                warnings: extra_warnings,
            })
        }
    }
}

impl SandboxProcess for ProcessWithWarnings {
    /// Merged at the call rather than when this wrapper was built: the wrapped
    /// process can report a cleanup failure long after that.
    fn warnings(&self) -> Vec<String> {
        let mut merged = self.inner.warnings();
        for warning in &self.warnings {
            if !merged.contains(warning) {
                merged.push(warning.clone());
            }
        }
        merged
    }

    fn output_metadata(&self) -> Option<&crate::mxc_common::models::SandboxOutputMetadata> {
        self.inner.output_metadata()
    }

    fn take_stdin(&mut self) -> Option<Box<dyn std::io::Write + Send>> {
        self.inner.take_stdin()
    }

    fn stdin_closer(&self) -> Option<Box<dyn StreamCloser>> {
        self.inner.stdin_closer()
    }

    fn take_native_stdio(&mut self) -> std::io::Result<Option<NativeStdio>> {
        self.inner.take_native_stdio()
    }

    fn is_pty(&self) -> bool {
        self.inner.is_pty()
    }

    fn pty_clone_reader(&self) -> std::io::Result<Box<dyn std::io::Read + Send>> {
        self.inner.pty_clone_reader()
    }

    fn pty_clone_reader_with_closer(&self) -> std::io::Result<PtyReaderWithCloser> {
        self.inner.pty_clone_reader_with_closer()
    }

    fn pty_take_writer(&self) -> std::io::Result<Box<dyn std::io::Write + Send>> {
        self.inner.pty_take_writer()
    }

    fn pty_resize(&self, size: PtySize) -> std::io::Result<()> {
        self.inner.pty_resize(size)
    }

    fn pty_size(&self) -> std::io::Result<PtySize> {
        self.inner.pty_size()
    }

    fn take_stdout(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
        self.inner.take_stdout()
    }

    fn take_stderr(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
        self.inner.take_stderr()
    }

    fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
        self.inner.try_wait()
    }

    fn id(&self) -> u32 {
        self.inner.id()
    }

    fn kill(&mut self) -> std::io::Result<()> {
        self.inner.kill()
    }

    fn kill_for_timeout(&mut self) -> std::io::Result<()> {
        self.inner.kill_for_timeout()
    }

    fn wait(&mut self) -> std::io::Result<i32> {
        self.inner.wait()
    }

    fn stdout_closer(&self) -> Option<Box<dyn StreamCloser>> {
        self.inner.stdout_closer()
    }

    fn stderr_closer(&self) -> Option<Box<dyn StreamCloser>> {
        self.inner.stderr_closer()
    }
}

#[cfg(test)]
mod telemetry_process_tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    enum TryWaitResult {
        Running,
        Exited(i32),
        TimedOut,
        Failed,
    }

    struct StubProcess {
        try_wait_result: TryWaitResult,
        wait_result: std::io::Result<i32>,
        kill_fails: bool,
        finalized: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
        metadata_read_before_finalization: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
        output_metadata: Option<crate::mxc_common::models::SandboxOutputMetadata>,
    }

    struct NativeStdioProbe {
        calls: Arc<AtomicUsize>,
        stdin_closer_calls: Arc<AtomicUsize>,
        pty_reader_calls: Arc<AtomicUsize>,
        pty_closer_calls: Arc<AtomicUsize>,
        timeout_kill_calls: Arc<AtomicUsize>,
    }

    struct CountingCloser {
        calls: Arc<AtomicUsize>,
    }

    impl StreamCloser for CountingCloser {
        fn close(&self) {
            self.calls.fetch_add(1, Ordering::SeqCst);
        }
    }

    impl SandboxProcess for NativeStdioProbe {
        fn take_native_stdio(&mut self) -> std::io::Result<Option<NativeStdio>> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            Ok(None)
        }

        fn take_stdin(&mut self) -> Option<Box<dyn std::io::Write + Send>> {
            None
        }

        fn stdin_closer(&self) -> Option<Box<dyn StreamCloser>> {
            self.stdin_closer_calls.fetch_add(1, Ordering::SeqCst);
            None
        }

        fn pty_clone_reader_with_closer(&self) -> std::io::Result<PtyReaderWithCloser> {
            self.pty_reader_calls.fetch_add(1, Ordering::SeqCst);
            Ok((
                Box::new(std::io::empty()),
                Some(Box::new(CountingCloser {
                    calls: Arc::clone(&self.pty_closer_calls),
                })),
            ))
        }

        fn take_stdout(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
            None
        }

        fn take_stderr(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
            None
        }

        fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
            Ok(Some(0))
        }

        fn id(&self) -> u32 {
            1
        }

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

        fn kill_for_timeout(&mut self) -> std::io::Result<()> {
            self.timeout_kill_calls.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }

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

    impl SandboxProcess for StubProcess {
        fn take_stdin(&mut self) -> Option<Box<dyn std::io::Write + Send>> {
            None
        }

        fn take_stdout(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
            None
        }

        fn take_stderr(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
            None
        }

        fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
            match self.try_wait_result {
                TryWaitResult::Running => Ok(None),
                TryWaitResult::Exited(code) => Ok(Some(code)),
                TryWaitResult::TimedOut => Err(std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    "timed out",
                )),
                TryWaitResult::Failed => Err(std::io::Error::other("poll failed")),
            }
        }

        fn id(&self) -> u32 {
            1
        }

        fn kill(&mut self) -> std::io::Result<()> {
            if self.kill_fails {
                Err(std::io::Error::other("kill failed"))
            } else {
                Ok(())
            }
        }

        fn wait(&mut self) -> std::io::Result<i32> {
            if let Some(finalized) = &self.finalized {
                finalized.store(true, std::sync::atomic::Ordering::SeqCst);
            }
            self.wait_result
                .as_ref()
                .copied()
                .map_err(|error| std::io::Error::new(error.kind(), error.to_string()))
        }

        fn output_metadata(&self) -> Option<&crate::mxc_common::models::SandboxOutputMetadata> {
            if let (Some(finalized), Some(read_before_finalization)) =
                (&self.finalized, &self.metadata_read_before_finalization)
            {
                if !finalized.load(std::sync::atomic::Ordering::SeqCst) {
                    read_before_finalization.store(true, std::sync::atomic::Ordering::SeqCst);
                }
            }
            self.output_metadata.as_ref()
        }
    }

    fn wrapped(try_wait_result: TryWaitResult) -> TelemetryProcess {
        wrapped_with_kill_failure(try_wait_result, false)
    }

    fn wrapped_with_kill_failure(
        try_wait_result: TryWaitResult,
        kill_fails: bool,
    ) -> TelemetryProcess {
        TelemetryProcess::new(
            Box::new(StubProcess {
                try_wait_result,
                wait_result: Ok(0),
                kill_fails,
                finalized: None,
                metadata_read_before_finalization: None,
                output_metadata: None,
            }),
            true,
            TelemetryMode::StateAware {
                backend: "test".to_string(),
                phase: "exec".to_string(),
                correlation_vector: String::new(),
                requested_sandbox_kind: None,
            },
            std::time::Instant::now(),
        )
    }

    #[test]
    fn process_wrappers_forward_stream_lifecycle_operations() {
        let telemetry_calls = Arc::new(AtomicUsize::new(0));
        let telemetry_closer_calls = Arc::new(AtomicUsize::new(0));
        let telemetry_pty_reader_calls = Arc::new(AtomicUsize::new(0));
        let telemetry_pty_closer_calls = Arc::new(AtomicUsize::new(0));
        let telemetry_timeout_calls = Arc::new(AtomicUsize::new(0));
        let mut telemetry = TelemetryProcess::new(
            Box::new(NativeStdioProbe {
                calls: Arc::clone(&telemetry_calls),
                stdin_closer_calls: Arc::clone(&telemetry_closer_calls),
                pty_reader_calls: Arc::clone(&telemetry_pty_reader_calls),
                pty_closer_calls: Arc::clone(&telemetry_pty_closer_calls),
                timeout_kill_calls: Arc::clone(&telemetry_timeout_calls),
            }),
            true,
            TelemetryMode::StateAware {
                backend: "test".to_string(),
                phase: "exec".to_string(),
                correlation_vector: String::new(),
                requested_sandbox_kind: None,
            },
            std::time::Instant::now(),
        );
        assert!(telemetry.take_native_stdio().unwrap().is_none());
        assert!(telemetry.stdin_closer().is_none());
        let (_, telemetry_pty_closer) = telemetry.pty_clone_reader_with_closer().unwrap();
        telemetry_pty_closer.unwrap().close();
        telemetry.kill_for_timeout().unwrap();
        assert_eq!(telemetry_calls.load(Ordering::SeqCst), 1);
        assert_eq!(telemetry_closer_calls.load(Ordering::SeqCst), 1);
        assert_eq!(telemetry_pty_reader_calls.load(Ordering::SeqCst), 1);
        assert_eq!(telemetry_pty_closer_calls.load(Ordering::SeqCst), 1);
        assert_eq!(telemetry_timeout_calls.load(Ordering::SeqCst), 1);

        let warning_calls = Arc::new(AtomicUsize::new(0));
        let warning_closer_calls = Arc::new(AtomicUsize::new(0));
        let warning_pty_reader_calls = Arc::new(AtomicUsize::new(0));
        let warning_pty_closer_calls = Arc::new(AtomicUsize::new(0));
        let warning_timeout_calls = Arc::new(AtomicUsize::new(0));
        let mut with_warnings = ProcessWithWarnings::wrap(
            Box::new(NativeStdioProbe {
                calls: Arc::clone(&warning_calls),
                stdin_closer_calls: Arc::clone(&warning_closer_calls),
                pty_reader_calls: Arc::clone(&warning_pty_reader_calls),
                pty_closer_calls: Arc::clone(&warning_pty_closer_calls),
                timeout_kill_calls: Arc::clone(&warning_timeout_calls),
            }),
            vec!["test warning".to_string()],
        );
        assert!(with_warnings.take_native_stdio().unwrap().is_none());
        assert!(with_warnings.stdin_closer().is_none());
        let (_, warning_pty_closer) = with_warnings.pty_clone_reader_with_closer().unwrap();
        warning_pty_closer.unwrap().close();
        with_warnings.kill_for_timeout().unwrap();
        assert_eq!(warning_calls.load(Ordering::SeqCst), 1);
        assert_eq!(warning_closer_calls.load(Ordering::SeqCst), 1);
        assert_eq!(warning_pty_reader_calls.load(Ordering::SeqCst), 1);
        assert_eq!(warning_pty_closer_calls.load(Ordering::SeqCst), 1);
        assert_eq!(warning_timeout_calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn alternate_spawn_dispatch_preserves_buffered_warnings() {
        let request = ExecutionRequest::default();
        let process = spawn_execution_request_with_logger_and(
            &request,
            Logger::new(Mode::Buffer),
            |_request, logger| {
                logger.warning_line("PTY spawn warning");
                Ok(Box::new(StubProcess {
                    try_wait_result: TryWaitResult::Running,
                    wait_result: Ok(0),
                    kill_fails: false,
                    finalized: None,
                    metadata_read_before_finalization: None,
                    output_metadata: None,
                }))
            },
        )
        .expect("alternate dispatcher should spawn");

        assert_eq!(process.warnings(), ["PTY spawn warning"]);
    }

    #[test]
    fn terminal_paths_consume_the_exactly_once_slot() {
        let mut waited = wrapped(TryWaitResult::Running);
        assert_eq!(waited.wait().unwrap(), 0);
        assert!(!waited.active);
        waited.kill().unwrap();
        assert!(!waited.active);

        let mut killed = wrapped(TryWaitResult::Running);
        killed.kill().unwrap();
        assert!(!killed.active);
        assert_eq!(killed.wait().unwrap(), 0);
        assert!(!killed.active);

        let mut exited = wrapped(TryWaitResult::Exited(7));
        assert_eq!(exited.try_wait().unwrap(), Some(7));
        assert!(!exited.active);

        let mut poll_failed = wrapped(TryWaitResult::Failed);
        assert!(poll_failed.try_wait().is_err());
        assert!(poll_failed.active);
        assert_eq!(poll_failed.wait().unwrap(), 0);
        assert!(!poll_failed.active);

        let mut timed_out = wrapped(TryWaitResult::TimedOut);
        assert_eq!(
            timed_out.try_wait().unwrap_err().kind(),
            std::io::ErrorKind::TimedOut
        );
        assert!(!timed_out.active);
    }

    #[test]
    fn failed_timeout_kill_preserves_timeout_when_exit_wins_the_race() {
        let mut process = wrapped_with_kill_failure(TryWaitResult::Exited(7), true);

        assert!(process.kill_for_timeout().is_err());
        let error = process
            .try_wait()
            .expect_err("the terminal race must retain timeout classification");

        assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
        assert!(!process.active);
    }

    #[test]
    fn state_aware_wait_timeout_preserves_timeout_failure_reason() {
        let timed_out = Err(std::io::Error::new(
            std::io::ErrorKind::TimedOut,
            "timed out",
        ));
        assert_eq!(
            TelemetryProcess::state_aware_wait_failure_reason(&timed_out),
            Some(telemetry::FailureReason::Timeout)
        );

        let failed = Err(std::io::Error::other("failed"));
        assert_eq!(
            TelemetryProcess::state_aware_wait_failure_reason(&failed),
            None
        );
    }

    #[test]
    fn nonterminal_poll_leaves_the_exactly_once_slot_active() {
        let mut process = wrapped(TryWaitResult::Running);
        assert_eq!(process.try_wait().unwrap(), None);
        assert!(process.active);
        process.emit_synthetic(SyntheticTerminal::Dropped);
        assert!(!process.active);
    }

    #[test]
    fn drop_observation_preserves_completed_exit_code() {
        let mut exited = StubProcess {
            try_wait_result: TryWaitResult::Exited(7),
            wait_result: Ok(0),
            kill_fails: false,
            finalized: None,
            metadata_read_before_finalization: None,
            output_metadata: None,
        };
        assert_eq!(observe_before_drop(&mut exited), DropDisposition::Exited(7));

        let mut running = StubProcess {
            try_wait_result: TryWaitResult::Running,
            wait_result: Ok(0),
            kill_fails: false,
            finalized: None,
            metadata_read_before_finalization: None,
            output_metadata: None,
        };
        assert_eq!(
            observe_before_drop(&mut running),
            DropDisposition::Abandoned
        );

        let mut failed = StubProcess {
            try_wait_result: TryWaitResult::Failed,
            wait_result: Ok(0),
            kill_fails: false,
            finalized: None,
            metadata_read_before_finalization: None,
            output_metadata: None,
        };
        assert_eq!(observe_before_drop(&mut failed), DropDisposition::Abandoned);

        let mut timed_out = StubProcess {
            try_wait_result: TryWaitResult::TimedOut,
            wait_result: Ok(0),
            kill_fails: false,
            finalized: None,
            metadata_read_before_finalization: None,
            output_metadata: None,
        };
        assert_eq!(
            observe_before_drop(&mut timed_out),
            DropDisposition::TimedOut
        );
    }

    #[test]
    fn failed_kill_leaves_the_exactly_once_slot_active() {
        let mut process = wrapped_with_kill_failure(TryWaitResult::Running, true);

        assert!(process.kill().is_err());
        assert!(process.active);
        assert_eq!(process.wait().unwrap(), 0);
        assert!(!process.active);
    }

    #[test]
    fn terminal_poll_does_not_wait_or_read_output_metadata() {
        let finalized = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let metadata_read_before_finalization =
            std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let mut process = TelemetryProcess::new(
            Box::new(StubProcess {
                try_wait_result: TryWaitResult::Exited(7),
                wait_result: Ok(7),
                kill_fails: false,
                finalized: Some(finalized.clone()),
                metadata_read_before_finalization: Some(metadata_read_before_finalization.clone()),
                output_metadata: None,
            }),
            true,
            TelemetryMode::StateAware {
                backend: "test".to_string(),
                phase: "exec".to_string(),
                correlation_vector: String::new(),
                requested_sandbox_kind: None,
            },
            std::time::Instant::now(),
        );

        assert_eq!(process.try_wait().unwrap(), Some(7));
        assert!(!finalized.load(std::sync::atomic::Ordering::SeqCst));
        assert!(!metadata_read_before_finalization.load(std::sync::atomic::Ordering::SeqCst));
        assert!(!process.active);
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn wait_error_preserves_finalized_metadata_and_reports_verbose_failure() {
        use crate::mxc_common::models::{CaptureDenialsOutput, SandboxOutputMetadata};

        let metadata = SandboxOutputMetadata {
            capture_denials: Some(CaptureDenialsOutput {
                kind: CaptureDenialsOutput::KIND.to_string(),
                output_path: "missing-denials.json".to_string(),
                exit_code: 0,
                total_denials: 0,
                denied_resources_truncated: false,
                etl_path: None,
            }),
            capture_denials_error: None,
        };
        let mut process = TelemetryProcess::new(
            Box::new(StubProcess {
                try_wait_result: TryWaitResult::Running,
                wait_result: Err(std::io::Error::other("retention failed")),
                kill_fails: false,
                finalized: Some(std::sync::Arc::new(std::sync::atomic::AtomicBool::new(
                    true,
                ))),
                metadata_read_before_finalization: Some(std::sync::Arc::new(
                    std::sync::atomic::AtomicBool::new(false),
                )),
                output_metadata: Some(metadata),
            }),
            true,
            TelemetryMode::OneShot {
                containment: ContainmentBackend::ProcessContainer,
                requested_sandbox_kind: None,
            },
            std::time::Instant::now(),
        );

        let response =
            process.completion_response(&Err(std::io::Error::other("retention failed")), true);
        assert!(response
            .output_metadata
            .as_deref()
            .and_then(|metadata| metadata.capture_denials.as_ref())
            .is_some());

        process.emit(&Err(std::io::Error::other("retention failed")));
        assert!(process
            .warnings()
            .iter()
            .any(|warning| warning.contains("could not open the verbose artifact")));
    }
}