cosca 0.8.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
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
//! `tokio::Command::spawn_suspended` and `tokio::SuspendedChild`, on real frozen children.
//!
//! Every Windows child is a windowless blocker (no console window on a developer's desktop): by
//! default `more.com`, which exits 0 on EOF, so a kill that sent nothing fails on how the child
//! ended; `findstr x` where a test needs its match or its exit 1. Tests that need a job, a
//! `TreeWalk` root or any other containment are named for it; the uncontained ones are the ones
//! that are safe to run on a developer's host.

use static_assertions::assert_impl_all;

use crate::test_child::Console;

use super::SuspendedChild;
#[cfg(not(windows))]
use crate::error::Error;

assert_impl_all!(SuspendedChild: Send);

/// The output of `future`, which must finish on its first poll: a refusal does, and needs no runtime.
fn answered_at_once<F: std::future::Future>(future: F) -> F::Output {
    let mut future = std::pin::pin!(future);
    match future
        .as_mut()
        .poll(&mut std::task::Context::from_waker(std::task::Waker::noop()))
    {
        std::task::Poll::Ready(output) => output,
        std::task::Poll::Pending => panic!("the future waited, where an answer at once was expected"),
    }
}

/// What `spawn_suspended` is refused with off Windows, before the runtime check: the same verdict
/// inside and outside a runtime.
#[cfg(not(windows))]
fn assert_spawn_suspended_is_refused() {
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.kill_on_drop(false);

    let err = answered_at_once(cmd.spawn_suspended()).expect_err("there is no frozen spawn here");

    let Error::Unsupported { op, .. } = &err else {
        panic!("expected Unsupported, got {err:?}");
    };
    assert_eq!(op, "spawn_suspended");
    assert!(
        !cmd.sync().kill_on_drop_flag(),
        "the refusal must leave the command as it was"
    );
}

#[cfg(not(windows))]
#[skuld::test]
fn spawn_suspended_is_unsupported_off_windows() {
    assert_spawn_suspended_is_refused();
}

#[cfg(not(windows))]
#[skuld::test]
async fn spawn_suspended_is_unsupported_off_windows_inside_a_runtime() {
    assert_spawn_suspended_is_refused();
}

#[cfg(windows)]
mod on_windows {
    use windows::Win32::Foundation::{CloseHandle, HANDLE};
    use windows::Win32::System::Threading::{
        OpenProcess, TerminateProcess, WaitForSingleObject, INFINITE, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
    };

    use super::Console;
    use crate::containment::windows::fault::{force_next, Step};
    use crate::error::{ChildFate, Error};
    use crate::test_frozen::{limit_flags, InitialThread, Remote};
    use crate::tokio::{Child, Command};
    use crate::Containment;

    const ERROR_ACCESS_DENIED: u32 = 5;

    /// A windowless blocker that exits 0 once its stdin closes; `raw` routes it to the raw
    /// `CreateProcessW` backend by giving it an `executable()`.
    fn blocker(raw: bool) -> Command {
        let more = crate::test_child::windows_more();
        let mut cmd = crate::test_child::tokio_command(Console::Hidden);
        cmd.args([&more]);
        if raw {
            cmd.executable(&more);
        }
        cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
        cmd.stdout(crate::Stdio::null()).expect("stdout null");
        cmd.stderr(crate::Stdio::null()).expect("stderr null");
        cmd
    }

    /// [`blocker`] with `findstr x`: it prints the matching line, and exits 1 on input with no
    /// match.
    fn findstr_blocker(raw: bool) -> Command {
        let mut cmd = crate::test_child::tokio_command(Console::Hidden);
        cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
        if raw {
            cmd.executable(crate::test_child::BLOCKER_ARGV[0]);
        }
        cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
        cmd.stdout(crate::Stdio::null()).expect("stdout null");
        cmd.stderr(crate::Stdio::null()).expect("stderr null");
        cmd
    }

    /// Both spawn backends, so a backend that drops the hold fails its own leg.
    const BACKENDS: [bool; 2] = [false, true];

    /// Whether a kill-on-drop teardown ran on the thread that made this: the hook sits on the
    /// teardown's kill, and reaches only the arming thread, so a teardown on the pool is not seen.
    struct TeardownHere {
        ran: std::rc::Rc<std::cell::Cell<bool>>,
        _armed: crate::oneshot_hook::Armed,
    }

    impl TeardownHere {
        fn get(&self) -> bool {
            self.ran.get()
        }
    }

    fn teardown_on_this_thread() -> TeardownHere {
        let ran = std::rc::Rc::new(std::cell::Cell::new(false));
        let armed = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterDropKill, {
            let ran = std::rc::Rc::clone(&ran);
            move || ran.set(true)
        });
        TeardownHere { ran, _armed: armed }
    }

    /// Kill `child`, then release its stdin: it exits 0 on EOF, so a kill that sent nothing fails
    /// the assertion on how it ended instead of the reap blocking for ever.
    async fn end(mut child: Child) {
        let stdin = child.stdin().expect("the blocker's piped stdin");
        child.kill().expect("kill the resumed child");
        drop(stdin);
        crate::test_child::assert_killed("the resumed child", child.wait().await.expect("reap the resumed child"));
    }

    /// The blocker for one `kill_on_drop` leg of a drop test. Stdin decides the child's fate: the
    /// `true` leg is `more.com` (exit 0 on EOF) and returns its write end, which the test drops only
    /// after the drop's kill, so the exit code tells a kill (1) from a release (0). The `false` leg
    /// pipes stdin and stdout, which [`drop_and_expect_it_runs`] keeps past the drop.
    fn drop_leg_blocker(kill_on_drop: bool) -> (Command, Option<crate::PipeWriter>) {
        if kill_on_drop {
            let mut cmd = blocker(false);
            cmd.kill_on_drop(true);
            let (stdin, writer) = crate::test_child::held_writer_stdin();
            cmd.stdin(stdin).expect("stdin");
            (cmd, Some(writer))
        } else {
            let mut cmd = findstr_blocker(false);
            cmd.kill_on_drop(false);
            cmd.stdout(crate::Stdio::pipe()).expect("stdout pipe");
            (cmd, None)
        }
    }

    /// Drop `child` (built by [`drop_leg_blocker`]`(true)`), then release its stdin: the drop's kill
    /// came first, so the child dies with the kill's exit code, or the test fails by assertion.
    fn drop_and_expect_it_killed(child: Child, writer: Option<crate::PipeWriter>, what: &str) {
        let remote = Remote::open(child.pid());
        drop(child);
        drop(writer);
        remote.wait_for_death();
        assert_eq!(remote.exit_code(), 1, "{what}: the drop must kill the resumed child");
    }

    /// Drop `child` (built by [`drop_leg_blocker`]`(false)`) and prove the drop did not kill it, by
    /// a round trip only a live child answers: a line in through its stdin, the match out of its
    /// stdout (`findstr x` prints it once its input ends). The drop issues its kill before the
    /// first byte is written, so a child the drop killed answers nothing, whenever it dies.
    async fn drop_and_expect_it_runs(mut child: Child, what: &str) {
        use ::tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
        let mut stdin = child.stdin().expect("piped stdin");
        let mut stdout = child.stdout().expect("piped stdout");

        drop(child);

        stdin
            .write_all(b"x\n")
            .await
            .unwrap_or_else(|e| panic!("{what}: kill_on_drop(false) must leave the child running: {e}"));
        drop(stdin);
        let mut answer = String::new();
        stdout.read_to_string(&mut answer).await.expect("read the answer");
        assert_eq!(
            answer.trim_end(),
            "x",
            "{what}: kill_on_drop(false) must leave the child running"
        );
    }

    // Refusals =====

    #[skuld::test]
    async fn spawn_suspended_with_elevate_is_unsupported_and_takes_nothing_from_the_command() {
        let mut cmd = blocker(false);
        cmd.elevate();

        let err = cmd
            .spawn_suspended()
            .await
            .expect_err("a frozen spawn cannot be elevated");

        let Error::Unsupported { op, .. } = &err else {
            panic!("expected Unsupported, got {err:?}");
        };
        assert!(op.contains("elevate"), "{op}");
        assert!(
            cmd.sync().fds().contains_key(&crate::Fd::STDIN),
            "a refusal before anything is taken must leave the stdio configuration in place"
        );
    }

    #[skuld::test]
    async fn spawn_suspended_with_breakaway_and_contain_is_unsupported() {
        let mut cmd = blocker(false);
        cmd.contain().breakaway_from_job();

        let err = cmd
            .spawn_suspended()
            .await
            .expect_err("breakaway and contain are refused");

        let Error::Unsupported { op, .. } = &err else {
            panic!("expected Unsupported, got {err:?}");
        };
        assert!(op.contains("breakaway_from_job"), "{op}");
    }

    /// Outside any runtime the spawn is a typed error, as `spawn` gives, and the command is as it
    /// was.
    #[skuld::test]
    fn async_spawn_suspended_outside_a_runtime_is_a_typed_error() {
        for kill_on_drop in [true, false] {
            let mut cmd = blocker(false);
            cmd.kill_on_drop(kill_on_drop);

            let err = super::answered_at_once(cmd.spawn_suspended()).expect_err("there is no runtime");

            assert!(err.fate().is_none(), "nothing started, got {err:?}");
            assert!(matches!(err, Error::Io(_)), "got {err:?}");
            assert_eq!(cmd.sync().kill_on_drop_flag(), kill_on_drop);
            assert!(!cmd.sync().flags_request().suspended);
        }
    }

    // The window =====

    /// Suspend count 1 is the kernel's statement that the initial thread has run nothing.
    #[skuld::test]
    async fn frozen_child_has_executed_no_instruction_before_resume() {
        for raw in BACKENDS {
            let frozen = blocker(raw).spawn_suspended().await.expect("spawn suspended");
            let thread = InitialThread::of(frozen.pid());
            assert_eq!(thread.suspend_count(), 1, "raw={raw}: frozen until resumed");

            let child = frozen.resume().await.expect("resume");

            assert_eq!(thread.suspend_count(), 0, "raw={raw}: running after resume");
            end(child).await;
        }
    }

    /// Something else started a running thread in the frozen child (an EDR agent, a debugger): the
    /// initial thread is still frozen exactly once, so the resume goes through.
    #[skuld::test]
    async fn resume_succeeds_when_another_party_started_a_running_thread_in_the_frozen_child() {
        for raw in BACKENDS {
            let frozen = blocker(raw).spawn_suspended().await.expect("spawn suspended");
            let _injected = crate::test_frozen::inject_running_thread_into_pid(frozen.pid());

            let child = frozen
                .resume()
                .await
                .unwrap_or_else(|e| panic!("raw={raw}: a running second thread failed the resume: {e:?}"));

            end(child).await;
        }
    }

    /// The frozen spawn is the async spawn: its child carries the async policy, as a plain async
    /// spawn's does (`the_async_spawn_hands_its_child_the_async_policy`).
    ///
    /// Mutant: the frozen spawn hands `spawn_frozen` the sync policy.
    #[skuld::test]
    async fn a_frozen_child_carries_the_async_policy() {
        use crate::child::owned::unreaped::DropKind;
        use crate::child::spawn::policy::SpawnPolicy;

        let _warn = crate::tokio::child::fault::warn_slow_teardowns_after(std::time::Duration::ZERO);
        for raw in BACKENDS {
            let frozen = blocker(raw).spawn_suspended().await.expect("spawn suspended");

            assert_eq!(
                frozen.child.inner.policy,
                SpawnPolicy {
                    teardown_warn_after: Some(std::time::Duration::ZERO),
                    unreaped_drop: DropKind::LetGo,
                },
                "raw={raw}"
            );
            end(frozen.resume().await.expect("resume")).await;
        }
    }

    #[skuld::test]
    async fn id_recorded_while_frozen_equals_the_resumed_childs_id() {
        for raw in BACKENDS {
            let frozen = blocker(raw).spawn_suspended().await.expect("spawn suspended");
            let recorded = frozen.id();

            let child = frozen.resume().await.expect("resume");

            assert_eq!(child.id(), recorded, "raw={raw}");
            end(child).await;
        }
    }

    #[skuld::test]
    async fn contained_frozen_child_is_inside_its_job_before_resume() {
        for raw in BACKENDS {
            let mut cmd = blocker(raw);
            cmd.contain();
            let frozen = cmd.spawn_suspended().await.expect("spawn suspended");
            assert!(
                frozen.test_job_handle_contains_self(),
                "raw={raw}: in its job while frozen"
            );

            let child = frozen.resume().await.expect("resume");

            assert_eq!(child.containment(), Containment::JobObject, "raw={raw}");
            assert!(child.test_job_handle_contains_self(), "raw={raw}");
            end(child).await;
        }
    }

    #[skuld::test]
    async fn uncontained_frozen_child_has_no_cosca_job_and_reports_containment_none() {
        for raw in BACKENDS {
            let frozen = blocker(raw).spawn_suspended().await.expect("spawn suspended");
            assert!(!frozen.test_job_handle_contains_self(), "raw={raw}: no containment job");
            assert_eq!(frozen.test_containment(), Containment::None, "raw={raw}");

            let child = frozen.resume().await.expect("resume");

            assert_eq!(child.containment(), Containment::None, "raw={raw}");
            end(child).await;
        }
    }

    /// The resumed child is armed as a `spawn()` child is, or not, as the command said.
    #[skuld::test]
    async fn contained_resumed_child_takes_the_commands_kill_on_drop() {
        for kill_on_drop in [true, false] {
            let mut cmd = blocker(false);
            cmd.contain().kill_on_drop(kill_on_drop);

            let child = cmd
                .spawn_suspended()
                .await
                .expect("spawn suspended")
                .resume()
                .await
                .expect("resume");

            assert_eq!(child.inner.kill_on_drop, kill_on_drop);
            let Some(job) = child.inner.tree.job_for_test() else {
                panic!("expected a job, got {:?}", child.inner.tree);
            };
            let kills_on_close =
                limit_flags(job).0 & windows::Win32::System::JobObjects::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.0 != 0;
            assert_eq!(kills_on_close, kill_on_drop, "kill_on_drop({kill_on_drop})");
            end(child).await;
        }
    }

    // The resumed child is a tokio child =====

    /// The pipes the frozen spawn made serve the resumed child: a line written to its stdin comes
    /// back on its stdout, and the exit is awaited. The echoed match and exit 0 show it ran:
    /// `findstr x` on input with no match exits 1.
    #[skuld::test]
    async fn a_resumed_child_serves_its_piped_stdin_and_stdout_and_is_awaited() {
        use ::tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
        for raw in BACKENDS {
            let mut cmd = findstr_blocker(raw);
            cmd.stdout(crate::Stdio::pipe()).expect("stdout pipe");
            let mut child = cmd
                .spawn_suspended()
                .await
                .expect("spawn suspended")
                .resume()
                .await
                .expect("resume");
            let mut stdin = child.stdin().expect("piped stdin");
            let mut stdout = child.stdout().expect("piped stdout");

            stdin.write_all(b"xyz\nabc\n").await.expect("write the child's stdin");
            drop(stdin);
            let mut answer = String::new();
            stdout
                .read_to_string(&mut answer)
                .await
                .expect("read the child's stdout");
            let status = child.wait().await.expect("await the exit");

            assert_eq!(answer.trim_end(), "xyz", "raw={raw}: only the matching line comes back");
            assert_eq!(status.code(), Some(0), "raw={raw}: findstr found a match");
        }
    }

    /// The resumed child's piped stderr carries what it writes: `findstr` names the file it cannot
    /// open there, and nothing reaches stdout.
    #[skuld::test]
    async fn a_resumed_child_serves_its_piped_stderr() {
        use ::tokio::io::AsyncReadExt as _;
        const MISSING: &str = "cosca-49-no-such-file.txt";
        for raw in BACKENDS {
            let mut cmd = crate::test_child::tokio_command(Console::Hidden);
            cmd.args(["findstr", "x", MISSING]);
            if raw {
                cmd.executable("findstr");
            }
            cmd.stdin(crate::Stdio::null()).expect("stdin null");
            cmd.stdout(crate::Stdio::pipe()).expect("stdout pipe");
            cmd.stderr(crate::Stdio::pipe()).expect("stderr pipe");
            let mut child = cmd
                .spawn_suspended()
                .await
                .expect("spawn suspended")
                .resume()
                .await
                .expect("resume");
            let mut stdout = child.stdout().expect("piped stdout");
            let mut stderr = child.stderr().expect("piped stderr");

            let (mut out, mut err) = (String::new(), String::new());
            stderr.read_to_string(&mut err).await.expect("read the child's stderr");
            stdout.read_to_string(&mut out).await.expect("read the child's stdout");
            let status = child.wait().await.expect("await the exit");

            assert!(err.contains(MISSING), "raw={raw}: stderr was {err:?}");
            assert_eq!(out, "", "raw={raw}");
            assert_ne!(status.code(), Some(0), "raw={raw}: the file does not exist");
        }
    }

    /// The command's `kill_on_drop` decides what dropping the resumed `Child` does: a resumed child
    /// that kept the frozen spawn's forced `true` would be killed by a command that opted out.
    ///
    /// The `true` leg's child dies with the kill's exit code, its stdin released only after the drop
    /// (see [`drop_and_expect_it_killed`]). The `false` leg proves the child alive after the drop with a
    /// round trip, not a look at the process.
    #[skuld::test]
    async fn death_watch_dropping_an_uncontained_resumed_child_follows_the_commands_kill_on_drop() {
        for kill_on_drop in [true, false] {
            let (mut cmd, writer) = drop_leg_blocker(kill_on_drop);
            let child = cmd
                .spawn_suspended()
                .await
                .expect("spawn suspended")
                .resume()
                .await
                .expect("resume");
            assert_eq!(child.inner.kill_on_drop, kill_on_drop);

            if kill_on_drop {
                drop_and_expect_it_killed(child, writer, "uncontained");
            } else {
                drop_and_expect_it_runs(child, "uncontained").await;
            }
        }
    }

    /// As above for every containment: a `TreeWalk` root and a job each follow the command too.
    #[skuld::test]
    async fn death_watch_dropping_a_contained_resumed_child_follows_the_commands_kill_on_drop() {
        for mode in [crate::ContainMode::TreeWalk, crate::ContainMode::Strongest] {
            for kill_on_drop in [true, false] {
                let (mut cmd, writer) = drop_leg_blocker(kill_on_drop);
                cmd.contain_with(mode);
                let child = cmd
                    .spawn_suspended()
                    .await
                    .expect("spawn suspended")
                    .resume()
                    .await
                    .expect("resume");
                assert_eq!(child.inner.kill_on_drop, kill_on_drop, "{mode:?}");

                if kill_on_drop {
                    drop_and_expect_it_killed(child, writer, &format!("{mode:?}"));
                } else {
                    drop_and_expect_it_runs(child, &format!("{mode:?}")).await;
                }
            }
        }
    }

    // Refusals before anything exists =====

    /// A program that does not exist fails as the same command's `spawn` does, and the command is as
    /// it was: the borrowed `kill_on_drop` and suspended request are put back.
    #[skuld::test]
    async fn spawn_suspended_of_a_nonexistent_program_fails_as_spawn_does_and_leaves_the_command_as_it_was() {
        fn io_kind(err: &Error) -> Option<std::io::ErrorKind> {
            match err {
                Error::Io(e) => Some(e.kind()),
                Error::MayHaveStarted { source, .. } => io_kind(source),
                _ => None,
            }
        }
        for raw in BACKENDS {
            for kill_on_drop in [true, false] {
                let mut cmd = crate::test_child::tokio_command(Console::Hidden);
                cmd.args(["cosca-49-no-such-program.exe"]);
                if raw {
                    cmd.executable("cosca-49-no-such-program.exe");
                }
                cmd.kill_on_drop(kill_on_drop);
                let plain = cmd.spawn().await.expect_err("there is no such program");

                let err = cmd.spawn_suspended().await.expect_err("there is no such program");

                assert_eq!(
                    io_kind(&err),
                    Some(std::io::ErrorKind::NotFound),
                    "raw={raw}: got {err:?}"
                );
                assert_eq!(io_kind(&err), io_kind(&plain), "raw={raw}");
                assert_eq!(err.fate(), plain.fate(), "raw={raw}");
                assert_eq!(cmd.sync().kill_on_drop_flag(), kill_on_drop, "raw={raw}");
                assert!(!cmd.sync().flags_request().suspended, "raw={raw}");
            }
        }
    }

    // Drop =====

    /// Hold `cmd`'s stdin (`more.com` exits 0 on EOF): the test releases it only after the drop, so
    /// the exit code tells the drop's kill (1) from a release (0).
    fn hold_stdin(cmd: &mut Command) -> crate::PipeWriter {
        let (stdin, writer) = crate::test_child::held_writer_stdin();
        cmd.stdin(stdin).expect("stdin");
        writer
    }

    /// The text of the one failure in the `cleanup` of the error of a resume whose teardown did not
    /// run: the cancellation, and that the child was dropped in the teardown's place. The cause
    /// (the release's or the disarm's failure) does not say it.
    #[track_caller]
    fn cancelled_teardown(err: &Error) -> String {
        let Error::MayHaveStarted { source, cleanup, .. } = err else {
            panic!("expected MayHaveStarted, got {err:?}");
        };
        let cleanup = cleanup.as_ref().expect("the cancelled teardown is in the cleanup");
        assert_eq!(cleanup.iter().len(), 1, "{cleanup:?}");
        let cause = crate::error::said(&**source);
        assert!(!cause.contains("dropped as its handle's drop does"), "{cause}");
        let said = crate::error::said(&**cleanup.first());
        assert!(said.contains("dropped as its handle's drop does"), "{said}");
        said
    }

    /// Release a frozen child's stdin and let its initial thread run, once the code under test has
    /// torn it down. A frozen child runs nothing, so the release alone cannot end it; with the thread
    /// resumed, a kill that sent nothing lets the blocker exit 0 and fail the exit-code assertion
    /// instead of leaving the wait for its death to hang. After a real kill the resume fails, and is
    /// ignored.
    fn release_and_expect_it_killed(thread: &InitialThread, writer: crate::PipeWriter, remote: &Remote, what: &str) {
        drop(writer);
        thread.resume_whatever_the_outcome();
        remote.wait_for_death();
        assert_eq!(remote.exit_code(), 1, "{what}: the teardown must kill the frozen child");
    }

    /// Drop `frozen`, then release it (see [`release_and_expect_it_killed`]). The drop is the async
    /// `Child`'s bounded one: it signals and returns, so the proof is the process object, opened
    /// while the frozen child pins the pid.
    fn drop_frozen_and_expect_it_killed(frozen: crate::tokio::SuspendedChild, writer: crate::PipeWriter, what: &str) {
        let remote = Remote::open(frozen.pid());
        let thread = InitialThread::of(frozen.pid());
        drop(frozen);
        release_and_expect_it_killed(&thread, writer, &remote, what);
    }

    /// A dropped frozen child is killed whatever `kill_on_drop` says. Nothing but the drop can end
    /// it (its stdin is released only after the drop).
    #[skuld::test]
    async fn death_watch_dropping_an_uncontained_frozen_child_kills_it_whatever_kill_on_drop_says() {
        for kill_on_drop in [false, true] {
            let mut cmd = blocker(false);
            cmd.kill_on_drop(kill_on_drop);
            let writer = hold_stdin(&mut cmd);
            let frozen = cmd.spawn_suspended().await.expect("spawn suspended");

            drop_frozen_and_expect_it_killed(frozen, writer, "uncontained");
        }
    }

    /// As above for a `TreeWalk` root and a job.
    #[skuld::test]
    async fn death_watch_dropping_a_contained_frozen_child_kills_it_whatever_kill_on_drop_says() {
        for mode in [crate::ContainMode::TreeWalk, crate::ContainMode::Strongest] {
            for kill_on_drop in [false, true] {
                let mut cmd = blocker(false);
                cmd.contain_with(mode).kill_on_drop(kill_on_drop);
                let writer = hold_stdin(&mut cmd);
                let frozen = cmd.spawn_suspended().await.expect("spawn suspended");

                drop_frozen_and_expect_it_killed(frozen, writer, &format!("{mode:?}"));
            }
        }
    }

    /// Piped stdout and stderr on a dropped frozen child neither hang the drop nor keep the child
    /// alive.
    #[skuld::test]
    async fn death_watch_dropping_a_frozen_child_with_piped_stdio_kills_it_without_hanging() {
        for raw in BACKENDS {
            let mut cmd = blocker(raw);
            cmd.stdout(crate::Stdio::pipe()).expect("stdout pipe");
            cmd.stderr(crate::Stdio::pipe()).expect("stderr pipe");
            let writer = hold_stdin(&mut cmd);
            let frozen = cmd.spawn_suspended().await.expect("spawn suspended");

            drop_frozen_and_expect_it_killed(frozen, writer, &format!("raw={raw}"));
        }
    }

    // Failure =====

    /// Occupy `rt`'s one blocking thread until the returned sender is used.
    fn hold_the_pool(
        rt: &::tokio::runtime::Runtime,
    ) -> (
        std::sync::mpsc::Sender<()>,
        ::tokio::task::JoinHandle<Result<(), std::sync::mpsc::RecvError>>,
    ) {
        let (release, held) = std::sync::mpsc::channel::<()>();
        (release, rt.spawn_blocking(move || held.recv()))
    }

    /// A resume that needs no teardown needs no runtime: a healthy frozen child is resumed on a
    /// plain thread, polled by hand.
    ///
    /// Mutant: `resume` asks for a runtime before the release.
    #[skuld::test]
    fn a_healthy_resume_outside_a_runtime_resumes_the_child() {
        let rt = crate::tokio::test_runtime::single_thread_pool_runtime();
        let mut cmd = blocker(false);
        cmd.contain().kill_on_drop(false);
        let frozen = rt.block_on(cmd.spawn_suspended()).expect("spawn suspended");

        let child = std::thread::spawn(move || super::answered_at_once(frozen.resume()))
            .join()
            .expect("resume outside a runtime must not panic")
            .expect("a healthy resume needs no runtime");

        rt.block_on(end(child));
    }

    /// With no runtime, a resume that needs a teardown cannot hop: the cancelled hop's task, which
    /// held the frozen child, is dropped on the calling thread, and the child is dropped as its
    /// handle's drop does. The release error stays the cause, and the error says there was no
    /// runtime.
    ///
    /// Mutant: `resume` answers the missing runtime in place of the release error.
    #[skuld::test]
    async fn a_failed_resume_outside_a_runtime_drops_the_child_on_the_calling_thread() {
        let mut cmd = blocker(false);
        let writer = hold_stdin(&mut cmd);
        let frozen = cmd.spawn_suspended().await.expect("spawn suspended");
        let remote = Remote::open(frozen.pid());
        let thread = InitialThread::of(frozen.pid());

        let (err, dropped_there) = std::thread::spawn(move || {
            let forced = force_next(Step::Resume, ERROR_ACCESS_DENIED);
            let dropped_there = teardown_on_this_thread();
            let err = super::answered_at_once(frozen.resume()).expect_err("the resume failed");
            drop(forced);
            (err, dropped_there.get())
        })
        .join()
        .expect("resume outside a runtime must not panic");

        assert_eq!(err.fate(), Some(ChildFate::Unknown), "{err:?}");
        assert_eq!(
            crate::error::first_os_code(&err),
            Some(ERROR_ACCESS_DENIED as i32),
            "{err:?}"
        );
        let said = cancelled_teardown(&err);
        assert!(said.contains("Tokio runtime"), "{said}");
        assert!(dropped_there, "the child was not dropped on the calling thread");
        release_and_expect_it_killed(&thread, writer, &remote, "a resume outside a runtime");
    }

    /// The commit of `kill_on_drop` after a good release is the disarm, which asks the job one
    /// question: it runs on the calling thread, so a pool that is busy does not hold the resume up.
    ///
    /// Mutant: `resume` commits `kill_on_drop` through the pool.
    #[skuld::test]
    fn resume_commits_kill_on_drop_without_the_pool() {
        let rt = crate::tokio::test_runtime::single_thread_pool_runtime();
        let mut cmd = blocker(false);
        cmd.contain().kill_on_drop(false);
        let frozen = rt.block_on(cmd.spawn_suspended()).expect("spawn suspended");
        let (release, hold) = hold_the_pool(&rt);

        let child = rt
            .block_on(async { super::answered_at_once(frozen.resume()) })
            .expect("resume");

        release.send(()).expect("release the held thread");
        rt.block_on(end(child));
        drop(hold);
    }

    /// A failed release whose teardown the runtime's shutdown cancels keeps the release as its cause,
    /// with the cancellation noted beside it and fate `Unknown`; the dropped child is killed.
    ///
    /// The runtime is dropped, and its handle entered: a hop onto its pool is cancelled at once, as
    /// one made during its shutdown is.
    ///
    /// Mutants: `resume` answers the cancellation in place of the release error; it says the
    /// teardown "did not run"; the fate is `Running` with no identity.
    #[skuld::test]
    fn a_failed_resume_whose_teardown_is_cancelled_keeps_the_release_error() {
        let rt = crate::tokio::test_runtime::single_thread_pool_runtime();
        let mut cmd = blocker(false);
        let writer = hold_stdin(&mut cmd);
        let frozen = rt.block_on(cmd.spawn_suspended()).expect("spawn suspended");
        let remote = Remote::open(frozen.pid());
        let thread = InitialThread::of(frozen.pid());
        let handle = rt.handle().clone();
        drop(rt);
        let _entered = handle.enter();
        let forced = force_next(Step::Resume, ERROR_ACCESS_DENIED);
        let dropped_here = teardown_on_this_thread();

        let err = super::answered_at_once(frozen.resume()).expect_err("the resume failed");
        drop(forced);

        assert_eq!(err.fate(), Some(ChildFate::Unknown), "{err:?}");
        assert_eq!(
            crate::error::first_os_code(&err),
            Some(ERROR_ACCESS_DENIED as i32),
            "{err:?}"
        );
        let said = cancelled_teardown(&err);
        assert!(said.contains("cancelled"), "{said}");
        assert!(
            dropped_here.get(),
            "the cancelled task's child was not dropped on this thread"
        );
        release_and_expect_it_killed(&thread, writer, &remote, "a cancelled teardown's child");
    }

    /// A disarm the job refused, whose teardown the runtime's shutdown cancels, fails as a refused
    /// disarm does when its teardown ran: the cause is the refusal itself, the cancellation is noted
    /// beside it, and the child is dropped by the cancelled task as its handle's drop does. This
    /// child asked for `kill_on_drop(false)`, but its disarm was refused, so the job still holds it
    /// armed: it is armed before the hop, so that the drop kills it as the teardown would have.
    ///
    /// Mutants: the cancelled arm wraps the refusal in a `Containment` cause of its own; the child
    /// is moved into the hop with `kill_on_drop` still false, so the drop leaves it running.
    #[skuld::test]
    fn a_refused_disarm_whose_teardown_is_cancelled_has_the_refusal_for_its_cause() {
        let rt = crate::tokio::test_runtime::single_thread_pool_runtime();
        let (frozen, writer) = frozen_with_a_refusing_job(&rt);
        let remote = Remote::open(frozen.pid());
        let handle = rt.handle().clone();
        drop(rt);
        let _entered = handle.enter();

        let err = super::answered_at_once(frozen.resume()).expect_err("the disarm was refused");

        let said = cancelled_teardown(&err);
        let (cause, fate, handed_back) = crate::test_child::expect_may_have_started_parts(err, ());
        assert!(matches!(cause, Error::Io(_)), "{cause:?}");
        assert_eq!(
            crate::error::first_os_code(&cause),
            Some(ERROR_ACCESS_DENIED as i32),
            "{cause:?}"
        );
        assert!(said.contains("cancelled"), "{said}");
        assert_eq!(fate, ChildFate::Unknown);
        assert!(handed_back.is_none());
        // The drop killed the child (a kill exits with 1), though it would end with its stdin (0).
        drop(writer);
        remote.wait_for_death();
        assert_eq!(remote.exit_code(), 1, "the cancelled task's drop must kill the child");
    }

    /// With no runtime a refused disarm cannot hop, so its teardown runs on the calling thread, as the
    /// drop's does: the error is the refusal alone, with the fate the teardown found, and the child
    /// is dead.
    ///
    /// Mutant: `resume` drops the child on the calling thread with `kill_on_drop` false, so it is
    /// left running, and the fate says nothing.
    #[skuld::test]
    fn a_refused_disarm_outside_a_runtime_is_torn_down_on_the_calling_thread() {
        let rt = crate::tokio::test_runtime::single_thread_pool_runtime();
        let (frozen, writer) = frozen_with_a_refusing_job(&rt);
        let remote = Remote::open(frozen.pid());

        let err = std::thread::spawn(move || super::answered_at_once(frozen.resume()))
            .join()
            .expect("resume outside a runtime must not panic")
            .expect_err("the disarm was refused");

        let said = crate::error::said(&err);
        let (cause, fate, handed_back) = crate::test_child::expect_may_have_started_parts(err, ());
        assert!(matches!(cause, Error::Io(_)), "{cause:?}");
        assert_eq!(
            crate::error::first_os_code(&cause),
            Some(ERROR_ACCESS_DENIED as i32),
            "{cause:?}"
        );
        assert!(!said.contains("Tokio runtime"), "{said}");
        assert!(matches!(fate, ChildFate::Killed | ChildFate::Reaped), "{fate:?}");
        assert!(handed_back.is_none());
        drop(writer);
        remote.wait_for_death();
        assert_eq!(remote.exit_code(), 1, "the teardown must kill the child");
    }

    /// A resumable frozen `kill_on_drop(false)` child whose job refuses the disarm, and the write end
    /// of its stdin.
    fn frozen_with_a_refusing_job(rt: &::tokio::runtime::Runtime) -> (crate::tokio::SuspendedChild, crate::PipeWriter) {
        let mut cmd = blocker(false);
        let writer = hold_stdin(&mut cmd);
        let mut frozen = rt.block_on(cmd.spawn_suspended()).expect("spawn suspended");
        frozen.child.inner.tree = crate::containment::Tree::contained(crate::containment::Mechanism::Job(
            crate::containment::windows::JobHandle::create_without_set_access_for_test(),
        ));
        frozen.wanted_kill_on_drop = false;
        (frozen, writer)
    }

    #[skuld::test]
    async fn a_failed_thread_resume_kills_the_child_and_reports_its_fate() {
        crate::tokio::test_runtime::assert_current_thread();
        let mut cmd = blocker(false);
        let writer = hold_stdin(&mut cmd);
        let frozen = cmd.spawn_suspended().await.expect("spawn suspended");
        let remote = Remote::open(frozen.pid());
        let thread = InitialThread::of(frozen.pid());
        let forced = force_next(Step::Resume, ERROR_ACCESS_DENIED);
        let torn_down_here = teardown_on_this_thread();

        let err = frozen.resume().await.expect_err("the resume was forced to fail");
        drop(forced);

        assert!(
            !torn_down_here.get(),
            "the failed resume's teardown ran on the runtime thread"
        );
        let fate = err
            .fate()
            .unwrap_or_else(|| panic!("expected MayHaveStarted, got {err:?}"));
        assert!(matches!(fate, ChildFate::Killed | ChildFate::Reaped), "{fate:?}");
        assert_eq!(
            crate::error::first_os_code(&err),
            Some(ERROR_ACCESS_DENIED as i32),
            "{err:?}"
        );
        release_and_expect_it_killed(&thread, writer, &remote, "a failed resume");
    }

    /// Async twin of the sync `a_failed_resume_of_a_child_without_a_front_sets_no_wrapper_flag`.
    ///
    /// Mutants: `resume` sets the flag from `report.is_some()` or from `may_run_as_another_user()`.
    #[skuld::test]
    async fn a_failed_resume_of_a_child_without_a_front_sets_no_wrapper_flag() {
        use crate::elevation::elevation_tests::{report, VIAS_WITHOUT_A_FRONT};
        crate::tokio::test_runtime::assert_current_thread();
        for via in VIAS_WITHOUT_A_FRONT {
            let mut cmd = blocker(false);
            let writer = hold_stdin(&mut cmd);
            cmd.set_elevation_report(Some(report(via.clone())));
            let frozen = cmd.spawn_suspended().await.expect("spawn suspended");
            let remote = Remote::open(frozen.pid());
            let thread = InitialThread::of(frozen.pid());
            let forced = force_next(Step::Resume, ERROR_ACCESS_DENIED);

            let err = frozen.resume().await.expect_err("the resume was forced to fail");
            drop(forced);

            assert!(
                matches!(
                    err,
                    Error::MayHaveStarted {
                        wrapper_elevated: false,
                        ..
                    }
                ),
                "{via:?}: {err:?}"
            );
            release_and_expect_it_killed(&thread, writer, &remote, "a failed resume");
        }
    }

    /// `resume` of a `kill_on_drop(false)` child whose job refuses the disarm fails with the
    /// refusal as its cause, and the child is dead: killed, not released (its stdin is held).
    ///
    /// Mutant: `resume` ignores the commit's failure and returns the child.
    #[skuld::test]
    async fn resume_whose_disarm_is_refused_fails_and_kills_the_child() {
        crate::tokio::test_runtime::assert_current_thread();
        let mut cmd = blocker(false);
        let writer = hold_stdin(&mut cmd);
        let mut frozen = cmd.spawn_suspended().await.expect("spawn suspended");
        frozen.child.inner.tree = crate::containment::Tree::contained(crate::containment::Mechanism::Job(
            crate::containment::windows::JobHandle::create_without_set_access_for_test(),
        ));
        frozen.wanted_kill_on_drop = false;
        let remote = Remote::open(frozen.pid());
        let torn_down_here = teardown_on_this_thread();

        let err = frozen.resume().await.expect_err("the disarm was refused");

        assert!(
            !torn_down_here.get(),
            "the refused disarm's teardown ran on the runtime thread"
        );
        let (cause, fate, handed_back) = crate::test_child::expect_may_have_started_parts(err, ());
        let Error::Io(io) = &cause else {
            panic!("expected Io, got {cause:?}");
        };
        assert_eq!(io.raw_os_error(), Some(ERROR_ACCESS_DENIED as i32), "{io:?}");
        assert_eq!(fate, ChildFate::Reaped);
        assert!(
            handed_back.is_none(),
            "the teardown ended the child, so none is handed back"
        );
        remote.wait_for_death();
        assert_eq!(remote.exit_code(), 1, "the teardown must kill the child");
        drop(writer);
    }

    /// Async twin of the sync `a_refused_disarm_of_a_child_without_a_front_sets_no_wrapper_flag`, through
    /// `resume`: a refused disarm of a child reported as a launch that leaves no front does not say it
    /// is a front's.
    ///
    /// Mutants: `resume` sets the flag from `report.is_some()` or from `may_run_as_another_user()`.
    #[skuld::test]
    async fn a_refused_disarm_of_a_resumed_child_without_a_front_sets_no_wrapper_flag() {
        use crate::elevation::elevation_tests::{report, VIAS_WITHOUT_A_FRONT};
        crate::tokio::test_runtime::assert_current_thread();
        for via in VIAS_WITHOUT_A_FRONT {
            let mut cmd = blocker(false);
            let writer = hold_stdin(&mut cmd);
            cmd.set_elevation_report(Some(report(via.clone())));
            let mut frozen = cmd.spawn_suspended().await.expect("spawn suspended");
            frozen.child.inner.tree = crate::containment::Tree::contained(crate::containment::Mechanism::Job(
                crate::containment::windows::JobHandle::create_without_set_access_for_test(),
            ));
            frozen.wanted_kill_on_drop = false;
            let remote = Remote::open(frozen.pid());

            let err = frozen.resume().await.expect_err("the disarm was refused");

            assert!(
                matches!(
                    err,
                    Error::MayHaveStarted {
                        wrapper_elevated: false,
                        ..
                    }
                ),
                "{via:?}: {err:?}"
            );
            assert_eq!(err.fate(), Some(ChildFate::Reaped), "{via:?}");
            remote.wait_for_death();
            assert_eq!(remote.exit_code(), 1, "{via:?}: the teardown must kill the child");
            drop(writer);
        }
    }

    /// Something else killed the frozen process. The process is observed dead (its handle is
    /// signalled) before `resume`, so the answer is not a race with the kill: an error with a fate,
    /// and no hang.
    #[skuld::test]
    async fn resume_after_an_external_kill_is_may_have_started_with_a_fate() {
        let frozen = blocker(false).spawn_suspended().await.expect("spawn suspended");
        // Opened while `frozen` holds the process, so the pid cannot name anything else.
        // SAFETY: plain Win32 calls; the handle is closed below.
        let victim: HANDLE = unsafe { OpenProcess(PROCESS_TERMINATE | PROCESS_SYNCHRONIZE, false, frozen.pid()) }
            .expect("open the frozen child");
        // SAFETY: `victim` is live.
        unsafe {
            TerminateProcess(victim, 1).expect("terminate the frozen child");
            // An event, not a timer: the process object signals when the process is gone.
            WaitForSingleObject(victim, INFINITE);
            _ = CloseHandle(victim);
        }

        let err = frozen.resume().await.expect_err("a dead child cannot be resumed");

        let fate = err
            .fate()
            .unwrap_or_else(|| panic!("expected MayHaveStarted, got {err:?}"));
        assert!(
            matches!(fate, ChildFate::Reaped | ChildFate::Killed | ChildFate::Gone),
            "{fate:?}"
        );
    }

    /// Something suspended the initial thread during the window. One resume would leave the child
    /// frozen, so `resume` must not return `Ok`.
    #[skuld::test]
    async fn resume_when_the_initial_thread_was_suspended_twice_kills_the_child_instead_of_returning_ok() {
        let mut cmd = blocker(false);
        let writer = hold_stdin(&mut cmd);
        let frozen = cmd.spawn_suspended().await.expect("spawn suspended");
        let remote = Remote::open(frozen.pid());
        let thread = InitialThread::of(frozen.pid());
        thread.suspend_once();

        let err = frozen
            .resume()
            .await
            .expect_err("the child is still frozen after one resume");

        assert!(err.fate().is_some(), "got {err:?}");
        release_and_expect_it_killed(&thread, writer, &remote, "a half-resumed child");
    }

    // The command =====

    /// The spawn borrows `kill_on_drop` and the suspended request for its duration only.
    #[skuld::test]
    async fn spawn_suspended_leaves_kill_on_drop_and_flags_as_they_were() {
        for kill_on_drop in [true, false] {
            let mut cmd = blocker(false);
            cmd.kill_on_drop(kill_on_drop);

            drop(cmd.spawn_suspended().await.expect("spawn suspended"));

            assert_eq!(cmd.sync().kill_on_drop_flag(), kill_on_drop);
            assert!(!cmd.sync().flags_request().suspended);
        }
    }

    /// A command used for `spawn_suspended` and then for `spawn` yields a running child. A child
    /// that stayed frozen never exits, so the wait is bounded by the suite slow-timeout.
    #[skuld::test]
    async fn death_watch_the_command_spawns_an_ordinary_child_after_a_frozen_one() {
        let mut cmd = findstr_blocker(false);
        drop(cmd.spawn_suspended().await.expect("spawn suspended"));

        // A spawn takes the stdio configuration out of the command, so the second one is given its own.
        cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
        let mut child = cmd.spawn().await.expect("an ordinary spawn");
        drop(child.stdin().expect("piped stdin"));

        let status = child.wait().await.expect("await the exit");

        assert_eq!(status.code(), Some(1), "the spawn after a frozen one must run");
    }

    #[skuld::test]
    async fn two_frozen_children_can_be_held_at_once_and_resumed_in_either_order() {
        for in_spawn_order in [true, false] {
            let a = blocker(false).spawn_suspended().await.expect("first");
            let b = blocker(false).spawn_suspended().await.expect("second");
            let (x, y) = if in_spawn_order { (a, b) } else { (b, a) };
            let (cx, cy) = (x.resume().await.expect("resume x"), y.resume().await.expect("resume y"));
            end(cx).await;
            end(cy).await;
        }
    }

    /// No lock is held across the window: an ordinary spawn completes while another child is frozen.
    #[skuld::test]
    async fn spawning_while_another_child_is_frozen_does_not_block() {
        let frozen = blocker(false).spawn_suspended().await.expect("spawn suspended");
        let other = blocker(false)
            .spawn()
            .await
            .expect("an ordinary spawn while one is frozen");
        end(other).await;
        drop(frozen);
    }

    #[skuld::test]
    async fn a_suspended_child_resumes_in_a_spawned_task() {
        let frozen = blocker(false).spawn_suspended().await.expect("spawn suspended");
        let child = ::tokio::spawn(async move { frozen.resume().await.expect("resume in a task") })
            .await
            .expect("the resuming task");
        end(child).await;
    }
}