mxc-sdk 1.1.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Handle-based ("streaming") sandbox execution.
//!
//! [`ScriptRunner`](crate::mxc_common::script_runner::ScriptRunner) owns the whole
//! lifecycle (spawn → wait → drain → return), which is fine for fire-and-
//! forget runs but cannot expose the running child. This module adds the
//! interface for the other model: spawn the sandboxed process and hand the
//! caller a [`SandboxProcess`] handle they can write to, read from, wait on,
//! and kill while it runs.
//!
//! As with [`ScriptRunner`](crate::mxc_common::script_runner::ScriptRunner), the traits
//! live in `mxc_common` (the cross-platform foundation) while the
//! implementations live in the per-backend crates — `mxc_common` must not
//! depend on any `backends/*` crate.

use std::io::{Read, Write};

use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{
    ExecutionRequest, FailurePhase, SandboxOutputMetadata, ScriptResponse,
};
use crate::mxc_common::mxc_error::MxcError;
use crate::mxc_common::script_runner::ScriptRunner;
use crate::mxc_common::validator::{
    validate_common, validate_network_policy_support, NetworkPolicySupport,
};

#[cfg(unix)]
pub type OwnedPipe = std::os::fd::OwnedFd;
#[cfg(windows)]
pub type OwnedPipe = std::os::windows::io::OwnedHandle;

/// A boxed reader for a pseudo-terminal's merged output.
pub type PtyReader = Box<dyn Read + Send>;

/// A pseudo-terminal reader paired with an optional out-of-band closer.
pub type PtyReaderWithCloser = (PtyReader, Option<Box<dyn StreamCloser>>);

/// Owned native endpoints for a sandbox process.
///
/// Each populated endpoint is an OS pipe handle/file descriptor with the
/// conventional direction: stdin is writable, while stdout and stderr are
/// readable. A backend may transfer its existing process pipes or synthesize
/// compatible pipes from another live stream transport.
///
/// Taking these endpoints atomically transfers stream ownership to the caller.
/// Unsupported streams remain `None`; the process retains only lifecycle
/// control, and its normal `take_*` methods return `None` afterward.
#[derive(Debug)]
pub struct NativeStdio {
    pub stdin: Option<OwnedPipe>,
    pub stdout: Option<OwnedPipe>,
    pub stderr: Option<OwnedPipe>,
}

impl NativeStdio {
    pub fn is_empty(&self) -> bool {
        self.stdin.is_none() && self.stdout.is_none() && self.stderr.is_none()
    }
}

/// Duplicates available native endpoints, then detaches their stream wrappers.
///
/// All duplication completes before any source is taken. If a duplication
/// fails, every source remains available to the sandbox process.
pub fn duplicate_and_take_native_stdio<I, O, E>(
    stdin: &mut Option<I>,
    stdout: &mut Option<O>,
    stderr: &mut Option<E>,
    duplicate_stdin: impl FnOnce(&I) -> std::io::Result<OwnedPipe>,
    duplicate_stdout: impl FnOnce(&O) -> std::io::Result<OwnedPipe>,
    duplicate_stderr: impl FnOnce(&E) -> std::io::Result<OwnedPipe>,
) -> std::io::Result<Option<NativeStdio>> {
    fn duplicate<T>(
        stream: Option<&T>,
        name: &str,
        duplicate: impl FnOnce(&T) -> std::io::Result<OwnedPipe>,
    ) -> std::io::Result<Option<OwnedPipe>> {
        stream.map(duplicate).transpose().map_err(|error| {
            std::io::Error::new(
                error.kind(),
                format!("failed to duplicate the {name} pipe: {error}"),
            )
        })
    }

    let stdio = NativeStdio {
        stdin: duplicate(stdin.as_ref(), "stdin", duplicate_stdin)?,
        stdout: duplicate(stdout.as_ref(), "stdout", duplicate_stdout)?,
        stderr: duplicate(stderr.as_ref(), "stderr", duplicate_stderr)?,
    };
    if stdio.is_empty() {
        return Ok(None);
    }

    stdin.take();
    stdout.take();
    stderr.take();
    Ok(Some(stdio))
}

/// A handle to a running sandboxed process.
///
/// Modelled on [`std::process::Child`]: the caller may `take_*` the std
/// streams to drive them directly (and is then responsible for draining any
/// stream they take, to avoid the child blocking on a full pipe), then
/// [`wait`](SandboxProcess::wait) for exit or [`kill`](SandboxProcess::kill)
/// it.
///
/// Any stdout/stderr stream the caller does **not** take is drained and
/// discarded internally by [`wait`](SandboxProcess::wait) so the child can
/// never block on a full pipe.
///
/// No pty is ever allocated; the streams are ordinary pipes.
///
/// # Abandoning a held-open stream (stdout/stderr closers)
///
/// A read on a taken stdout/stderr only ends at EOF — when **every** write end
/// closes. A backgrounded descendant that inherited the pipe can hold its write
/// end open long after the foreground command exits, so a caller blocked on
/// such a read would hang until that descendant finally exits. A plain
/// [`kill`](SandboxProcess::kill) would unblock it but also tear the descendant
/// down, defeating any grace window for backgrounded work.
///
/// [`stdout_closer`](SandboxProcess::stdout_closer) /
/// [`stderr_closer`](SandboxProcess::stderr_closer) hand back a
/// [`StreamCloser`] for exactly this case: calling
/// [`close`](StreamCloser::close) makes an in-flight or subsequent read on that
/// stream return EOF (`Ok(0)`) promptly **without** terminating the child.
///
/// # Pipe-deadlock contract (read both ends concurrently)
///
/// stdout and stderr are independent OS pipes with bounded kernel buffers. If
/// one is left undrained while the child keeps writing to it, the child blocks
/// on the full pipe — and if the reader is meanwhile blocked waiting on the
/// *other* stream (or on the child to exit), the two deadlock. So both ends
/// must be consumed **concurrently**, never one fully then the other:
///
/// - **Implementors** of [`wait`](SandboxProcess::wait) must drain the
///   not-taken stdout and stderr on separate threads (or non-blocking I/O)
///   before/while waiting on the child — not sequentially. The in-tree
///   backends spawn one reader thread per stream.
/// - **Callers** that `take_stdout()` *and* `take_stderr()` and read them to
///   EOF must likewise read them on separate threads; reading one to EOF
///   before touching the other can hang on output-heavy children. Taking only
///   one stream (leaving the other for `wait()` to drain) is always safe.
pub trait SandboxProcess: Send {
    /// Warnings associated with this sandbox, such as a policy that
    /// intentionally relaxes containment, an unavailable telemetry route, or a
    /// cleanup step that failed after the process exited.
    ///
    /// Owned rather than borrowed so a wrapper can merge its own warnings with
    /// the ones it wraps at the moment of the call. A snapshot taken when the
    /// wrapper was built would freeze out anything reported later.
    fn warnings(&self) -> Vec<String> {
        Vec::new()
    }

    /// Structured outputs available after the process has reached a terminal
    /// state and backend teardown has completed.
    fn output_metadata(&self) -> Option<&SandboxOutputMetadata> {
        None
    }

    /// Transfer owned native stdio endpoints to the caller.
    ///
    /// Backends may return existing process pipes or synthesize OS pipes from
    /// another live stream transport. Backends that cannot provide compatible
    /// endpoints return `Ok(None)`.
    fn take_native_stdio(&mut self) -> std::io::Result<Option<NativeStdio>> {
        Ok(None)
    }

    /// Whether this process is attached to a caller-driven pseudo-terminal.
    fn is_pty(&self) -> bool {
        false
    }

    /// Clone a reader for the pseudo-terminal's merged output stream.
    fn pty_clone_reader(&self) -> std::io::Result<PtyReader> {
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "this sandbox process is not attached to a pseudo-terminal",
        ))
    }

    /// Clone a reader and its optional out-of-band closer for the
    /// pseudo-terminal's merged output stream.
    fn pty_clone_reader_with_closer(&self) -> std::io::Result<PtyReaderWithCloser> {
        self.pty_clone_reader().map(|reader| (reader, None))
    }

    /// Take the pseudo-terminal input writer. This may succeed only once.
    ///
    /// On Unix, dropping the writer requests terminal EOF by writing the
    /// configured `VEOF` character while the terminal is in canonical mode.
    /// Raw-mode applications receive no pipe-style half-close and must define
    /// their own input-completion protocol.
    fn pty_take_writer(&self) -> std::io::Result<Box<dyn Write + Send>> {
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "this sandbox process is not attached to a pseudo-terminal",
        ))
    }

    /// Resize the pseudo-terminal.
    fn pty_resize(&self, _size: PtySize) -> std::io::Result<()> {
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "this sandbox process is not attached to a pseudo-terminal",
        ))
    }

    /// Return the current pseudo-terminal dimensions.
    fn pty_size(&self) -> std::io::Result<PtySize> {
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "this sandbox process is not attached to a pseudo-terminal",
        ))
    }

    /// Take ownership of the child's stdin so the caller can write to it.
    /// Returns `None` if already taken. Drop the writer to send EOF.
    fn take_stdin(&mut self) -> Option<Box<dyn Write + Send>>;

    /// A closer that interrupts the stdin stream returned by
    /// [`take_stdin`](SandboxProcess::take_stdin), including an in-flight
    /// blocking write. The default returns `None`.
    fn stdin_closer(&self) -> Option<Box<dyn StreamCloser>> {
        None
    }

    /// Take ownership of the child's stdout for live reading. Returns `None`
    /// if already taken. A taken stream is **not** drained by
    /// [`wait`](SandboxProcess::wait).
    fn take_stdout(&mut self) -> Option<Box<dyn Read + Send>>;

    /// Take ownership of the child's stderr for live reading. Returns `None`
    /// if already taken. A taken stream is **not** drained by
    /// [`wait`](SandboxProcess::wait).
    fn take_stderr(&mut self) -> Option<Box<dyn Read + Send>>;

    /// Non-blocking exit check. `Ok(Some(code))` if the child has exited,
    /// `Ok(None)` if it is still running.
    fn try_wait(&mut self) -> std::io::Result<Option<i32>>;

    /// The OS process id of the sandboxed child (its PID on Unix, process id
    /// on Windows). Useful for external monitoring or a caller-driven process
    /// tree kill.
    ///
    /// Only meaningful while the child is alive. On Unix the PID may be reused
    /// by an unrelated process once the child has been reaped (by
    /// [`wait`](SandboxProcess::wait)), so do not act on it after waiting.
    fn id(&self) -> u32;

    /// Request termination of the sandboxed process **and its descendants**
    /// (a process-tree kill). On Unix the child leads its own process group
    /// and this signals the whole group (an immediate `SIGKILL`, no graceful
    /// `SIGTERM` first); on Windows it terminates the job
    /// object the child is assigned to. Reaping happens in
    /// [`wait`](SandboxProcess::wait).
    fn kill(&mut self) -> std::io::Result<()>;

    /// Request termination because the execution deadline elapsed.
    ///
    /// The default uses the same process-tree termination primitive as
    /// [`kill`](SandboxProcess::kill). Wrappers may override this to preserve
    /// timeout-specific reporting while delegating the actual termination.
    /// Once requested, a later successful terminal observation is reported as
    /// timed out; callers must invoke this only after the deadline elapsed.
    fn kill_for_timeout(&mut self) -> std::io::Result<()> {
        self.kill()
    }

    /// Block until the child exits (honouring the request's `scriptTimeout`,
    /// where `0` means wait forever) and return its exit code.
    ///
    /// Any stdout/stderr the caller did not `take_*` is drained and discarded
    /// while waiting so the child can never block on a full pipe. If the
    /// timeout elapses, the workload is terminated and
    /// [`ErrorKind::TimedOut`](std::io::ErrorKind::TimedOut) is returned.
    ///
    /// **How far that termination reaches is the implementation's to state.**
    /// The process-spawning implementations kill the whole tree — the child
    /// leads its own process group on Unix and is assigned a job object on
    /// Windows. An implementation whose only primitive is the foreground
    /// process (the state-aware exec adapter, over a backend with no tree API)
    /// confirms that process and leaves descendants to whatever owns the
    /// sandbox's lifetime. Do not read `TimedOut` as a tree kill without
    /// checking the backend.
    ///
    /// Implementors must drain the not-taken stdout and stderr **concurrently**
    /// (not one then the other) — see the type-level pipe-deadlock contract.
    fn wait(&mut self) -> std::io::Result<i32>;

    /// A closer that EOFs the stdout stream returned by
    /// [`take_stdout`](SandboxProcess::take_stdout), on demand, **without**
    /// killing the child — for abandoning a stream a backgrounded descendant is
    /// holding open past the foreground command's exit (a plain
    /// [`kill`](SandboxProcess::kill) would also take that descendant down).
    ///
    /// Intended for a stream the caller has **taken** and is reading:
    /// [`close`](StreamCloser::close) abandons that read, and may be called
    /// concurrently with it. [`wait`](SandboxProcess::wait) already cancels its
    /// own internal safety-drain of any *not-taken* stream once the child exits,
    /// so a closer is only useful on a taken stream — firing one on a not-taken
    /// stream while the child is still producing output would stall the child on
    /// a full pipe. Returns `None` when the stream is not interruptible — e.g.
    /// inherited stdio ([`StdioMode::Inherit`]), where the caller never reads
    /// from a handle stream. The default returns `None`.
    fn stdout_closer(&self) -> Option<Box<dyn StreamCloser>> {
        None
    }

    /// A closer for the stderr stream — see
    /// [`stdout_closer`](SandboxProcess::stdout_closer). The default returns
    /// `None`.
    fn stderr_closer(&self) -> Option<Box<dyn StreamCloser>> {
        None
    }
}

/// Interrupts blocking I/O on one of a [`SandboxProcess`]'s standard streams.
///
/// For stdout/stderr, [`close`](StreamCloser::close) makes an in-flight or
/// subsequent read return EOF (`Ok(0)`) promptly without terminating the
/// child. For stdin, it closes/cancels the writable path so an in-flight write
/// can return and the child can observe EOF.
///
/// Obtained from [`stdin_closer`](SandboxProcess::stdin_closer),
/// [`stdout_closer`](SandboxProcess::stdout_closer), or
/// [`stderr_closer`](SandboxProcess::stderr_closer). `Send + Sync` so a
/// watchdog thread separate from the blocked I/O can hold and fire it.
pub trait StreamCloser: Send + Sync {
    /// Promptly interrupt the stream this closer was minted for. Idempotent and
    /// safe to call after the stream has already completed or been dropped.
    fn close(&self);
}

/// Spawn a thread that reads `reader` to EOF and discards it, so a stream the
/// caller did not take can't block the child on a full pipe. Returns `None`
/// when there is nothing to drain.
pub fn spawn_discard<R: Read + Send + 'static>(
    reader: Option<R>,
) -> Option<std::thread::JoinHandle<()>> {
    reader.map(|mut r| {
        std::thread::spawn(move || {
            let _ = std::io::copy(&mut r, &mut std::io::sink());
        })
    })
}

/// Join a [`spawn_discard`] thread (no-op when absent).
pub fn join_discard(handle: Option<std::thread::JoinHandle<()>>) {
    if let Some(t) = handle {
        let _ = t.join();
    }
}

/// Take a readable stream out of an `Option` and box it as a trait object, for
/// the [`SandboxProcess::take_stdout`] / [`SandboxProcess::take_stderr`]
/// accessors. Returns `None` if already taken.
pub fn take_boxed_read<R: Read + Send + 'static>(
    slot: &mut Option<R>,
) -> Option<Box<dyn Read + Send>> {
    slot.take().map(|r| Box::new(r) as Box<dyn Read + Send>)
}

/// Take a writable stream out of an `Option` and box it as a trait object, for
/// the [`SandboxProcess::take_stdin`] accessor. Returns `None` if already taken.
pub fn take_boxed_write<W: Write + Send + 'static>(
    slot: &mut Option<W>,
) -> Option<Box<dyn Write + Send>> {
    slot.take().map(|w| Box::new(w) as Box<dyn Write + Send>)
}

/// Clone a stored stream canceller and box it as a [`StreamCloser`], for the
/// [`SandboxProcess::stdout_closer`] / [`SandboxProcess::stderr_closer`]
/// accessors. Returns `None` when there is no canceller (non-streamed stdio).
pub fn boxed_closer<C: StreamCloser + Clone + 'static>(
    canceller: &Option<C>,
) -> Option<Box<dyn StreamCloser>> {
    canceller
        .clone()
        .map(|c| Box::new(c) as Box<dyn StreamCloser>)
}

/// Join a not-taken stdout/stderr discard thread from
/// [`wait`](SandboxProcess::wait), first cancelling its read so the join can't
/// block. When the stream was drained (a [`spawn_discard`] thread exists), fire
/// `canceller` before joining: a backgrounded descendant holding the pipe's
/// write end open past the foreground child's exit would otherwise keep the
/// discard [`io::copy`](std::io::copy) — and thus `wait()` — from ever returning
/// under a wait-forever (`scriptTimeout == 0`) timeout. The drained output is
/// discarded regardless, so cutting it short is harmless.
///
/// Call *after* the child has exited (so its own output has drained normally).
/// A no-op when the caller took the stream (`drain` is `None`): there is no
/// thread to join, and the canceller must not fire while the caller may still be
/// reading.
pub fn cancel_and_join_discard<C: StreamCloser>(
    drain: Option<std::thread::JoinHandle<()>>,
    canceller: &Option<C>,
) {
    if drain.is_some() {
        if let Some(canceller) = canceller {
            canceller.close();
        }
    }
    join_discard(drain);
}

/// SIGKILL a Unix child's process group. The backends make the child a group
/// leader (`setsid()` / `process_group(0)`), so `-pid` targets that group —
/// never the host's — killing the leader and every descendant.
///
/// No graceful `SIGTERM` first: it's unreliable (a `/bin/sh -c …` wrapper parked
/// in a foreground `wait` defers it and finishes the script) and sandboxed code
/// isn't owed a cleanup window. The **leader is killed before the group**: a
/// `-pid`-only sweep races — the kernel can kill a descendant first, waking the
/// shell to run one more command (seen as post-timeout output on the Inherit
/// path) before its own signal lands — so we make the leader's SIGKILL pending
/// first. The caller reaps the direct child afterwards.
#[cfg(unix)]
pub fn group_kill(child: &mut std::process::Child) -> std::io::Result<()> {
    // The child is unreaped, so its pid (== pgid) can't have been recycled.
    let pid = child.id() as i32;
    send_sigkill(pid)?; // leader first
    send_sigkill(-pid)?; // then its group
    Ok(())
}

#[cfg(unix)]
pub fn open_caller_stdio() -> [bool; 3] {
    // SAFETY: F_GETFD only reads this process's descriptor flags.
    std::array::from_fn(|fd| unsafe { libc::fcntl(fd as libc::c_int, libc::F_GETFD) } >= 0)
}

/// `caller_stdio` must come from [`open_caller_stdio`] before the launch opens any descriptors.
#[cfg(unix)]
pub fn keep_caller_stdio_across_exec(command: &mut std::process::Command, caller_stdio: [bool; 3]) {
    use std::os::unix::process::CommandExt;

    // Hosts such as Node mark their stdio close-on-exec, which would leave the
    // workload with none. A slot the caller had closed may now hold the
    // launch's own error pipe, which must still close on exec.
    // SAFETY: fcntl is async-signal-safe and only changes the forked child's descriptors.
    unsafe {
        command.pre_exec(move || {
            for fd in (0..3).filter(|&fd| caller_stdio[fd]) {
                let fd = fd as libc::c_int;
                let flags = libc::fcntl(fd, libc::F_GETFD);
                if flags >= 0
                    && flags & libc::FD_CLOEXEC != 0
                    && libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) < 0
                {
                    return Err(std::io::Error::last_os_error());
                }
            }
            Ok(())
        });
    }
}

/// `SIGKILL` `target` (a pid, or a negative pgid), treating the "already gone"
/// outcomes as success. The caller only invokes this on its own still-unreaped
/// child (so the pid/pgid can't have been recycled), which leaves two benign
/// errno: `ESRCH` (no such process/group — already exited) and `EPERM`, which on
/// macOS a redundant kill of an exited-but-not-yet-reaped child's group reports
/// instead of `ESRCH`. Any other error propagates, so a genuinely failed signal
/// isn't misreported as a successful kill.
#[cfg(unix)]
fn send_sigkill(target: i32) -> std::io::Result<()> {
    // SAFETY: `kill(2)` with a plain pid / negative pgid — just integers.
    if unsafe { libc::kill(target, libc::SIGKILL) } == 0 {
        return Ok(());
    }
    let err = std::io::Error::last_os_error();
    match err.raw_os_error() {
        Some(libc::ESRCH) | Some(libc::EPERM) => Ok(()),
        _ => Err(err),
    }
}

/// Outcome of [`wait_with_timeout`]: the child exited, the deadline passed, or
/// the wait itself failed.
#[cfg(unix)]
pub enum WaitError {
    Timeout,
    Io(std::io::Error),
}

/// Wait for `child` to exit. With a timeout we poll (rather than add an async
/// runtime), starting at a short interval and backing off to a cap: a quick
/// child is detected within ~a millisecond instead of always paying a full
/// fixed tick, while a long run settles to an inexpensive cadence. Each sleep is
/// clamped to the time remaining so even sub-interval timeouts fire on time.
/// Shared by the Unix run-to-completion backends.
#[cfg(unix)]
pub fn wait_with_timeout(
    child: &mut std::process::Child,
    timeout: Option<std::time::Duration>,
) -> Result<std::process::ExitStatus, WaitError> {
    use std::time::{Duration, Instant};
    // Poll interval grows from this floor to the cap (doubling each idle tick),
    // trading low exit-detection latency for short runs against an inexpensive
    // cadence for long ones.
    const MIN_POLL: Duration = Duration::from_millis(1);
    const MAX_POLL: Duration = Duration::from_millis(50);

    let Some(deadline) = timeout.map(|d| Instant::now() + d) else {
        return child.wait().map_err(WaitError::Io);
    };
    let mut interval = MIN_POLL;
    loop {
        match child.try_wait() {
            Ok(Some(status)) => return Ok(status),
            Ok(None) => {
                let now = Instant::now();
                if now >= deadline {
                    return Err(WaitError::Timeout);
                }
                std::thread::sleep((deadline - now).min(interval));
                interval = (interval * 2).min(MAX_POLL);
            }
            Err(error) => return Err(WaitError::Io(error)),
        }
    }
}

/// Dimensions of a pseudo-terminal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PtySize {
    pub rows: u16,
    pub cols: u16,
    pub pixel_width: u16,
    pub pixel_height: u16,
}

impl Default for PtySize {
    fn default() -> Self {
        Self {
            rows: 24,
            cols: 80,
            pixel_width: 0,
            pixel_height: 0,
        }
    }
}

impl PtySize {
    /// Reject dimensions that cannot be represented by supported PTY backends.
    pub fn validate(self) -> Result<(), MxcError> {
        const MAX_DIMENSION: u16 = i16::MAX as u16;

        if self.rows == 0
            || self.cols == 0
            || self.rows > MAX_DIMENSION
            || self.cols > MAX_DIMENSION
        {
            return Err(MxcError::malformed_request(
                "PTY rows and columns must be between 1 and 32767",
            ));
        }
        Ok(())
    }
}

/// How a [`SandboxBackend`] wires the sandboxed child's standard streams.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StdioMode {
    /// stdin/stdout/stderr are fresh pipes the caller drives via the handle's
    /// `take_*` accessors (the `mxc` library / streaming path). The child sees
    /// no TTY and leads its own process group so it can be tree-terminated.
    Pipes,
    /// The child inherits the current process's stdin/stdout/stderr (the CLI
    /// executor path): its output goes straight to the binary's own stdio, so
    /// the child sees a TTY exactly when the binary does. The returned handle's
    /// `take_*` all return `None`; [`wait`](SandboxProcess::wait) just waits.
    Inherit,
    /// The backend allocates a pseudo-terminal, attaches the sandboxed process
    /// to its secondary side, and retains the primary side for the returned
    /// handle. Output is a single merged stream.
    Pty(PtySize),
}

/// A containment backend that spawns a sandboxed process and hands back a
/// [`SandboxProcess`] handle — the single entry point for starting a sandbox.
///
/// The caller picks how the child's stdio is wired ([`StdioMode`]) and then
/// drives the handle: stream it ([`StdioMode::Pipes`]) or just
/// [`wait`](SandboxProcess::wait) ([`StdioMode::Inherit`]). The `mxc` library
/// calls this directly with [`StdioMode::Pipes`]; the CLI executor binaries
/// reach it through the [`Runner`] bridge.
pub trait SandboxBackend {
    /// Declares optional network policy features this backend fully enforces.
    ///
    /// Return a named feature constant or compose constants with `|`. Use
    /// [`NetworkPolicySupport::ALL`] only when every feature is enforced.
    fn network_policy_support(&self) -> NetworkPolicySupport {
        NetworkPolicySupport::default()
    }

    /// Validates shared network support and backend-specific constraints.
    ///
    /// Override to add backend-specific checks. Implementations must first call
    /// `validate_network_policy_support(request, self.network_policy_support())`.
    fn validate(&self, request: &ExecutionRequest) -> Result<(), ScriptResponse> {
        validate_network_policy_support(request, self.network_policy_support())?;
        Ok(())
    }

    /// Apply this backend's containment and spawn the sandboxed process with
    /// stdio wired per `stdio`, returning a handle. On a validation or spawn
    /// failure returns a [`ScriptResponse`] carrying the error.
    ///
    /// Implementations must apply shared and backend-specific request validation
    /// before launching. Environmental checks may instead be enforced by the
    /// actual sandbox setup, before the workload is allowed to run.
    fn spawn(
        &mut self,
        request: &ExecutionRequest,
        logger: &mut Logger,
        stdio: StdioMode,
    ) -> Result<Box<dyn SandboxProcess>, ScriptResponse>;

    /// Optional post-exit diagnostics for the run-to-completion (binary) path:
    /// when the child exits non-zero, return a more actionable error message
    /// (e.g. a known AppContainer filesystem-permission failure). Default: none.
    /// The streaming/library path does not call this.
    fn diagnose_exit(&self, _request: &ExecutionRequest, _exit_code: i32) -> Option<String> {
        None
    }
}

/// The single run-to-completion bridge: adapts any [`SandboxBackend`] to the
/// [`ScriptRunner`] contract the executor binaries (`wxc-exec` / `lxc-exec` /
/// `mxc-exec-mac`) dispatch over.
///
/// It spawns the child with [`StdioMode::Inherit`] — so the sandboxed process
/// reads/writes the binary's own stdio directly (a TTY when the binary has
/// one) — and [`wait`](SandboxProcess::wait)s for exit, mapping the outcome to
/// a [`ScriptResponse`]. Because the child streams straight to the binary's
/// stdio, `standard_out`/`standard_err` stay empty (the binaries already print
/// those, which is then a no-op).
///
/// This is the *only* run-to-completion logic for these backends; the backends
/// themselves expose just [`SandboxBackend::spawn`].
pub struct Runner<B>(B);

impl<B> Runner<B> {
    /// Wrap a [`SandboxBackend`] so it can be dispatched as a [`ScriptRunner`].
    pub fn new(backend: B) -> Self {
        Self(backend)
    }
}

impl<B: SandboxBackend> Runner<B> {
    fn wait_for_child(
        &self,
        request: &ExecutionRequest,
        logger: &mut Logger,
        child: Result<Box<dyn SandboxProcess>, ScriptResponse>,
    ) -> ScriptResponse {
        let mut child = match child {
            Ok(child) => child,
            Err(response) => return response,
        };

        let mut response = match child.wait() {
            Ok(exit_code) => {
                let mut response = ScriptResponse {
                    exit_code,
                    output_metadata: child.output_metadata().cloned().map(Box::new),
                    failure_phase: if exit_code == 0 {
                        FailurePhase::None
                    } else {
                        FailurePhase::ProcessExited
                    },
                    ..Default::default()
                };
                // Let the backend enrich a non-zero exit with an actionable
                // message (the child streamed live, so the response is otherwise
                // empty).
                if exit_code != 0 {
                    if let Some(msg) = self.0.diagnose_exit(request, exit_code) {
                        logger.log_line(&format!("Error: Launch diagnostic: {msg}"));
                        response.standard_err.push_str(&msg);
                        response.error_message = msg;
                    }
                }
                response
            }
            Err(e) if e.kind() == std::io::ErrorKind::TimedOut => ScriptResponse {
                exit_code: -1,
                error_message: format!("script timed out after {}ms: {e}", request.script_timeout),
                output_metadata: child.output_metadata().cloned().map(Box::new),
                failure_phase: FailurePhase::Timeout,
                ..Default::default()
            },
            Err(e) => {
                let mut response = ScriptResponse::error(&format!("wait failed: {e}"));
                response.output_metadata = child.output_metadata().cloned().map(Box::new);
                response
            }
        };
        // Backends report failures after exit, such as cleanup, here.
        response.extend_warnings(child.warnings());
        response
    }
}

impl<B: SandboxBackend> ScriptRunner for Runner<B> {
    fn validate_runner(&self, request: &ExecutionRequest) -> Result<(), ScriptResponse> {
        self.0.validate(request)
    }

    fn execute(&mut self, request: &ExecutionRequest, logger: &mut Logger) -> ScriptResponse {
        // Direct callers have not passed through ScriptRunner::run, so use the
        // backend's validation-safe public spawn path.
        let child = self.0.spawn(request, logger, StdioMode::Inherit);
        self.wait_for_child(request, logger, child)
    }

    fn run(&mut self, request: &ExecutionRequest, logger: &mut Logger) -> ScriptResponse {
        // A dry-run has no spawn call to enforce validation. Normal execution
        // uses SandboxBackend::spawn, the single validation-safe launch path.
        if request.dry_run {
            if let Err(response) = validate_common(request) {
                return response;
            }
            if let Err(response) = self.validate_runner(request) {
                return response;
            }
            return ScriptResponse {
                exit_code: 0,
                ..Default::default()
            };
        }

        self.execute(request, logger)
    }
}

#[cfg(test)]
mod runner_tests {
    use std::fs::File;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    use crate::mxc_common::logger::Mode;

    use super::*;

    #[derive(Default)]
    struct CompletedProcess {
        wait_error: Option<std::io::Error>,
        warnings: Vec<String>,
    }

    struct NativePipeSource;

    fn duplicate_test_pipe() -> std::io::Result<OwnedPipe> {
        Ok(File::open(std::env::current_exe()?)?.into())
    }

    #[test]
    fn native_stdio_transfer_detaches_sources_only_after_all_duplicates_succeed() {
        let mut stdin = Some(NativePipeSource);
        let mut stdout = Some(NativePipeSource);
        let mut stderr = Some(NativePipeSource);

        let stdio = duplicate_and_take_native_stdio(
            &mut stdin,
            &mut stdout,
            &mut stderr,
            |_| duplicate_test_pipe(),
            |_| duplicate_test_pipe(),
            |_| duplicate_test_pipe(),
        )
        .unwrap()
        .unwrap();

        assert!(stdio.stdin.is_some());
        assert!(stdio.stdout.is_some());
        assert!(stdio.stderr.is_some());
        assert!(stdin.is_none());
        assert!(stdout.is_none());
        assert!(stderr.is_none());
    }

    #[test]
    fn pty_size_rejects_dimensions_outside_signed_16_bit_range() {
        for size in [
            PtySize {
                rows: 0,
                cols: 80,
                pixel_width: 0,
                pixel_height: 0,
            },
            PtySize {
                rows: 24,
                cols: 0,
                pixel_width: 0,
                pixel_height: 0,
            },
            PtySize {
                rows: i16::MAX as u16 + 1,
                cols: 80,
                pixel_width: 0,
                pixel_height: 0,
            },
            PtySize {
                rows: 24,
                cols: i16::MAX as u16 + 1,
                pixel_width: 0,
                pixel_height: 0,
            },
        ] {
            let error = size
                .validate()
                .expect_err("out-of-range dimensions must fail");
            assert_eq!(
                error.code,
                crate::mxc_common::mxc_error::MxcErrorCode::MalformedRequest
            );
        }
        assert!(PtySize::default().validate().is_ok());
        assert!(PtySize {
            rows: i16::MAX as u16,
            cols: i16::MAX as u16,
            pixel_width: 0,
            pixel_height: 0,
        }
        .validate()
        .is_ok());
    }

    #[test]
    fn native_stdio_transfer_returns_none_when_all_sources_are_empty() {
        let mut stdin: Option<NativePipeSource> = None;
        let mut stdout: Option<NativePipeSource> = None;
        let mut stderr: Option<NativePipeSource> = None;

        let stdio = duplicate_and_take_native_stdio(
            &mut stdin,
            &mut stdout,
            &mut stderr,
            |_| duplicate_test_pipe(),
            |_| duplicate_test_pipe(),
            |_| duplicate_test_pipe(),
        )
        .unwrap();

        assert!(stdio.is_none());
    }

    #[test]
    fn native_stdio_transfer_preserves_sources_when_duplication_fails() {
        let mut stdin = Some(NativePipeSource);
        let mut stdout = Some(NativePipeSource);
        let mut stderr = Some(NativePipeSource);

        let result = duplicate_and_take_native_stdio(
            &mut stdin,
            &mut stdout,
            &mut stderr,
            |_| duplicate_test_pipe(),
            |_| Err(std::io::Error::other("duplicate failed")),
            |_| duplicate_test_pipe(),
        );

        assert!(result.is_err());
        assert!(stdin.is_some());
        assert!(stdout.is_some());
        assert!(stderr.is_some());
    }

    impl SandboxProcess for CompletedProcess {
        fn warnings(&self) -> Vec<String> {
            self.warnings.clone()
        }

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

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

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

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

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

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

        fn wait(&mut self) -> std::io::Result<i32> {
            self.wait_error.take().map_or(Ok(0), Err)
        }
    }

    struct CountingBackend {
        validations: Arc<AtomicUsize>,
        direct_spawns: Arc<AtomicUsize>,
        reject_validation: bool,
    }

    impl SandboxBackend for CountingBackend {
        fn validate(&self, _request: &ExecutionRequest) -> Result<(), ScriptResponse> {
            self.validations.fetch_add(1, Ordering::Relaxed);
            if self.reject_validation {
                Err(ScriptResponse::error("backend validation failed"))
            } else {
                Ok(())
            }
        }

        fn spawn(
            &mut self,
            request: &ExecutionRequest,
            _logger: &mut Logger,
            _stdio: StdioMode,
        ) -> Result<Box<dyn SandboxProcess>, ScriptResponse> {
            validate_common(request)?;
            self.validate(request)?;
            self.direct_spawns.fetch_add(1, Ordering::Relaxed);
            Ok(Box::new(CompletedProcess::default()))
        }
    }

    struct CleanupWarningBackend;

    impl SandboxBackend for CleanupWarningBackend {
        fn validate(&self, _request: &ExecutionRequest) -> Result<(), ScriptResponse> {
            Ok(())
        }

        fn spawn(
            &mut self,
            _request: &ExecutionRequest,
            _logger: &mut Logger,
            _stdio: StdioMode,
        ) -> Result<Box<dyn SandboxProcess>, ScriptResponse> {
            Ok(Box::new(CompletedProcess {
                warnings: vec!["cleanup failed".to_string()],
                ..Default::default()
            }))
        }
    }

    #[test]
    fn runner_reports_process_warnings_with_the_exit_code() {
        let mut runner = Runner::new(CleanupWarningBackend);
        let request = ExecutionRequest {
            script_code: "echo hello".to_string(),
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);

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

        assert_eq!(response.exit_code, 0);
        assert_eq!(response.warnings(), ["cleanup failed"]);
    }

    #[test]
    fn runner_capture_timeout_preserves_wait_diagnostics() {
        let runner = Runner::new(CountingBackend {
            validations: Arc::default(),
            direct_spawns: Arc::default(),
            reject_validation: false,
        });
        let request = ExecutionRequest {
            script_timeout: 1000,
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);
        let diagnostic =
            "process timed out; captureDenials teardown also failed: report write failed";
        let child = CompletedProcess {
            wait_error: Some(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                diagnostic,
            )),
            warnings: vec!["capture failed after timeout".to_string()],
        };

        let response = runner.wait_for_child(&request, &mut logger, Ok(Box::new(child)));

        assert_eq!(response.exit_code, -1);
        assert_eq!(response.failure_phase, FailurePhase::Timeout);
        assert!(response
            .error_message
            .contains("script timed out after 1000ms"));
        assert!(response.error_message.contains(diagnostic));
        assert_eq!(response.warnings(), ["capture failed after timeout"]);
        assert!(response.output_metadata.is_none());
    }

    #[test]
    fn runner_execute_validates_direct_callers() {
        let validations = Arc::new(AtomicUsize::new(0));
        let direct_spawns = Arc::new(AtomicUsize::new(0));
        let mut runner = Runner::new(CountingBackend {
            validations: Arc::clone(&validations),
            direct_spawns: Arc::clone(&direct_spawns),
            reject_validation: false,
        });
        let request = ExecutionRequest {
            script_code: "echo hello".to_string(),
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);

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

        assert_eq!(response.exit_code, 0);
        assert_eq!(validations.load(Ordering::Relaxed), 1);
        assert_eq!(direct_spawns.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn runner_execute_applies_shared_validation() {
        let validations = Arc::new(AtomicUsize::new(0));
        let direct_spawns = Arc::new(AtomicUsize::new(0));
        let mut runner = Runner::new(CountingBackend {
            validations: Arc::clone(&validations),
            direct_spawns: Arc::clone(&direct_spawns),
            reject_validation: false,
        });
        let request = ExecutionRequest::default();
        let mut logger = Logger::new(Mode::Buffer);

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

        assert_eq!(response.exit_code, -1);
        assert_eq!(validations.load(Ordering::Relaxed), 0);
        assert_eq!(direct_spawns.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn runner_run_validates_once() {
        let validations = Arc::new(AtomicUsize::new(0));
        let direct_spawns = Arc::new(AtomicUsize::new(0));
        let mut runner = Runner::new(CountingBackend {
            validations: Arc::clone(&validations),
            direct_spawns: Arc::clone(&direct_spawns),
            reject_validation: false,
        });
        let request = ExecutionRequest {
            script_code: "echo hello".to_string(),
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);

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

        assert_eq!(response.exit_code, 0);
        assert_eq!(validations.load(Ordering::Relaxed), 1);
        assert_eq!(direct_spawns.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn runner_run_dry_run_validates_without_spawning() {
        let validations = Arc::new(AtomicUsize::new(0));
        let direct_spawns = Arc::new(AtomicUsize::new(0));
        let mut runner = Runner::new(CountingBackend {
            validations: Arc::clone(&validations),
            direct_spawns: Arc::clone(&direct_spawns),
            reject_validation: false,
        });
        let request = ExecutionRequest {
            script_code: "echo hello".to_string(),
            dry_run: true,
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);

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

        assert_eq!(response.exit_code, 0);
        assert_eq!(validations.load(Ordering::Relaxed), 1);
        assert_eq!(direct_spawns.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn runner_run_backend_validation_failure_does_not_spawn() {
        let validations = Arc::new(AtomicUsize::new(0));
        let direct_spawns = Arc::new(AtomicUsize::new(0));
        let mut runner = Runner::new(CountingBackend {
            validations: Arc::clone(&validations),
            direct_spawns: Arc::clone(&direct_spawns),
            reject_validation: true,
        });
        let request = ExecutionRequest {
            script_code: "echo hello".to_string(),
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);

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

        assert_eq!(response.exit_code, -1);
        assert_eq!(response.error_message, "backend validation failed");
        assert_eq!(validations.load(Ordering::Relaxed), 1);
        assert_eq!(direct_spawns.load(Ordering::Relaxed), 0);
    }
}

#[cfg(all(test, unix))]
mod tests {
    use super::{keep_caller_stdio_across_exec, open_caller_stdio, wait_with_timeout, WaitError};
    use std::process::Command;
    use std::time::{Duration, Instant};

    #[test]
    fn closed_caller_stdio_does_not_block_spawn() {
        const HOST_ENV: &str = "MXC_CLOSED_STDIO_HOST";
        let test_name = format!(
            "{}::closed_caller_stdio_does_not_block_spawn",
            module_path!().split_once("::").unwrap().1
        );
        if std::env::var_os(HOST_ENV).is_none() {
            let output = Command::new(std::env::current_exe().unwrap())
                .args(["--exact", &test_name, "--nocapture", "--test-threads=1"])
                .env(HOST_ENV, "1")
                .output()
                .expect("run closed-stdio host");
            assert!(
                output.status.success(),
                "closed-stdio host failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            assert!(
                String::from_utf8_lossy(&output.stdout).contains("running 1 test"),
                "closed-stdio host did not run the test"
            );
            return;
        }

        // With fds 0 and 1 closed, Rust's launch-error pipe takes both slots.
        // SAFETY: closes this child host's own stdin and stdout.
        unsafe {
            libc::close(0);
            libc::close(1);
        }
        let mut command = Command::new("sleep");
        command.arg("5");
        keep_caller_stdio_across_exec(&mut command, open_caller_stdio());
        let started = Instant::now();
        let mut child = command.spawn().expect("spawn sleep");
        let elapsed = started.elapsed();
        let _ = child.kill();
        let _ = child.wait();
        assert!(
            elapsed < Duration::from_secs(2),
            "spawn blocked for {elapsed:?} until the workload exited"
        );
    }

    #[test]
    fn wait_with_timeout_detects_quick_exit_promptly() {
        // A child that exits almost immediately is reaped well before a generous
        // deadline -- the adaptive poll starts in the millisecond range, so the
        // detection latency is small (the old fixed 50ms tick was the worst case).
        let mut child = Command::new("true").spawn().expect("spawn true");
        let start = Instant::now();
        let status = match wait_with_timeout(&mut child, Some(Duration::from_secs(10))) {
            Ok(status) => status,
            Err(_) => panic!("a quick child must exit, not time out"),
        };
        assert!(status.success(), "`true` exits 0");
        assert!(
            start.elapsed() < Duration::from_secs(1),
            "quick exit should be detected promptly, took {:?}",
            start.elapsed()
        );
    }

    #[test]
    fn wait_with_timeout_fires_at_the_deadline() {
        // A long-running child hits the timeout branch at (not before) the
        // deadline, even though the deadline is shorter than the poll cap.
        let mut child = Command::new("sleep")
            .arg("30")
            .spawn()
            .expect("spawn sleep");
        let start = Instant::now();
        let result = wait_with_timeout(&mut child, Some(Duration::from_millis(200)));
        let elapsed = start.elapsed();
        let _ = child.kill();
        let _ = child.wait();
        assert!(matches!(result, Err(WaitError::Timeout)), "should time out");
        assert!(
            elapsed >= Duration::from_millis(200),
            "must not fire before the deadline, fired at {elapsed:?}"
        );
        assert!(
            elapsed < Duration::from_secs(2),
            "should fire near the deadline, fired at {elapsed:?}"
        );
    }

    #[test]
    fn wait_with_timeout_without_deadline_waits_for_exit() {
        // A `None` timeout blocks until the child exits.
        let mut child = Command::new("true").spawn().expect("spawn true");
        let status = match wait_with_timeout(&mut child, None) {
            Ok(status) => status,
            Err(_) => panic!("blocking wait must return the exit status"),
        };
        assert!(status.success());
    }
}