cosca 0.6.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
// Unit tests for dispatch root-detection and mechanism-selection logic.
// These test pure functions directly — no process-env mutation required.

use super::is_nested;

/// Without the marker the process is the root (not nested).
#[skuld::test]
fn is_nested_without_marker_is_false() {
    assert!(!is_nested(false));
}

/// With the marker the process is already inside a contained tree (nested).
#[skuld::test]
fn is_nested_with_marker_is_true() {
    assert!(is_nested(true));
}

// unix_setup_for mutual-exclusivity tests (S3) =====

/// `ContainMode::Session` must select `UnixSetup::Session` (setsid) — never
/// `ProcessGroup`. This is the critical S3 invariant: calling both setsid AND
/// setpgid/process_group(0) on the same Command would cause EPERM.
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_session_selects_setsid() {
    use super::{unix_setup_for, UnixSetup};
    use crate::containment::ContainMode;
    assert_eq!(unix_setup_for(Some(ContainMode::Session)), UnixSetup::Session);
}

/// `ContainMode::Strongest` must select `UnixSetup::ProcessGroup` — never Session.
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_strongest_selects_process_group() {
    use super::{unix_setup_for, UnixSetup};
    use crate::containment::ContainMode;
    assert_eq!(unix_setup_for(Some(ContainMode::Strongest)), UnixSetup::ProcessGroup);
}

/// `ContainMode::TreeWalk` must select `UnixSetup::None` — NO pre-spawn process
/// group. TreeWalk exists to catch children that escape a process group via
/// `setsid`/`setpgid`, so the root must not be put in a group; teardown is by
/// identity at kill time.
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_treewalk_selects_none() {
    use super::{unix_setup_for, UnixSetup};
    use crate::containment::ContainMode;
    assert_eq!(unix_setup_for(Some(ContainMode::TreeWalk)), UnixSetup::None);
}

/// Uncontained (`None` mode) must select `UnixSetup::ProcessGroup` (the
/// prepare path gates on `mode.is_some()` before calling this, but the
/// default fallback is well-defined).
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_none_mode_selects_process_group() {
    use super::{unix_setup_for, UnixSetup};
    assert_eq!(unix_setup_for(None), UnixSetup::ProcessGroup);
}

// Attached actionability + nested delegation =====

#[skuld::test]
fn attached_is_actionable() {
    use super::Attached;
    // No teardown mechanism -> not actionable (the _tree guard rejects these).
    assert!(!Attached::None.is_actionable()); // uncontained / lone
    assert!(!Attached::Delegated.is_actionable());
    // Every real mechanism is actionable. Cheap variants are built inline; Cgroup/JobObject
    // need an OS handle, so a test-only constructor builds one (asserted on its own platform).
    assert!(Attached::TreeWalk(crate::identity::ProcessId::current()).is_actionable());
    #[cfg(unix)]
    assert!(Attached::ProcessGroup(0).is_actionable());
    #[cfg(target_os = "linux")]
    assert!(Attached::Cgroup(crate::containment::cgroup::CgroupLeaf::placeholder_for_test()).is_actionable());
    #[cfg(windows)]
    assert!(Attached::JobObject(crate::containment::windows::JobHandle::create_empty_for_test()).is_actionable());
}

/// `Child::kill_tree`/`terminate_tree`'s pgid-recycle precondition assert gates on this
/// predicate, not on `Attached::ProcessGroup` alone (`src/child.rs`, `src/tokio/child.rs`) —
/// a macOS `FdMarker` that carries a pgid must be covered too, since it fires `killpg`
/// unconditionally on pass 1 of every sweep, exactly the hazard this precondition guards.
#[cfg(unix)]
#[skuld::test]
fn attached_carries_recyclable_pgid() {
    use super::Attached;
    assert!(!Attached::None.carries_recyclable_pgid());
    assert!(!Attached::Delegated.carries_recyclable_pgid());
    assert!(!Attached::TreeWalk(crate::identity::ProcessId::current()).carries_recyclable_pgid());
    assert!(Attached::ProcessGroup(0).carries_recyclable_pgid());
    #[cfg(target_os = "linux")]
    assert!(
        !Attached::Cgroup(crate::containment::cgroup::CgroupLeaf::placeholder_for_test()).carries_recyclable_pgid()
    );
}

/// The macOS-specific half of `attached_carries_recyclable_pgid`: an `FdMarker` must track
/// its OWN `pgid`, not the mechanism's mere presence — `TreeWalk` mode creates no pgid at
/// all (`Marker::pgid: None`), so a marker built for it must read `false` here exactly like
/// `Attached::TreeWalk` itself, while a marker built for any grouped mode (`pgid: Some(_)`)
/// must read `true`, matching `Attached::ProcessGroup`.
#[cfg(target_os = "macos")]
#[skuld::test]
fn attached_fd_marker_carries_recyclable_pgid_tracks_its_own_pgid() {
    use std::os::fd::{AsFd, AsRawFd};

    use super::Attached;

    fn marker_with_pgid(pgid: Option<i32>) -> crate::containment::fdmarker::Marker {
        let (read, write) = std::io::pipe().expect("pipe");
        let handle = crate::containment::fdmarker::pipe_handle_of(write.as_fd()).expect("handle");
        let read_handle = crate::containment::fdmarker::pipe_handle_of(read.as_fd()).expect("read handle");
        let prepared = crate::containment::fdmarker::PreparedMarker {
            read: std::os::fd::OwnedFd::from(read),
            handle,
            read_handle,
            fd: write.as_fd().as_raw_fd(),
        };
        crate::containment::fdmarker::Marker::new(
            prepared,
            crate::containment::fdmarker::fdmarker_tests::inert_root(),
            pgid,
        )
    }

    assert!(Attached::FdMarker(marker_with_pgid(Some(1234))).carries_recyclable_pgid());
    assert!(!Attached::FdMarker(marker_with_pgid(None)).carries_recyclable_pgid());
}

/// Drives the real `attach()` nested arms (not a hand-built variant): a nested
/// (`!is_root`) contained spawn must yield BOTH halves of the delegated pair —
/// `Containment::Delegated` and `Attached::Delegated` — for a kernel mechanism
/// (Strongest) and TreeWalk, so `containment()` predicts the `_tree` error.
#[skuld::test]
fn nested_attach_is_delegated() {
    use super::{attach, Attached, Prepared};
    use crate::containment::{ContainMode, Containment};

    fn spawn_trivial() -> std::process::Child {
        // attach()'s nested arms don't touch the child, so an exited child is fine. Held for
        // the fork itself: a fork landing while a `fdmarker_tests.rs` test's marker write end
        // is transiently open would inherit it into this not-yet-`exec`'d process, and a
        // concurrent sweep could then find and SIGKILL it.
        #[cfg(unix)]
        return crate::test_spawn::spawn(&mut std::process::Command::new("true")).expect("spawn true");
        #[cfg(windows)]
        return crate::test_spawn::spawn(std::process::Command::new("cmd").args(["/C", "exit"])).expect("spawn cmd");
    }

    for mode in [ContainMode::Strongest, ContainMode::TreeWalk] {
        let mut child = spawn_trivial();
        let prepared = Prepared {
            mode: Some(mode),
            is_root: false, // nested member
            #[cfg(target_os = "linux")]
            cgroup_leaf: None,
            #[cfg(target_os = "macos")]
            marker: None,
            #[cfg(windows)]
            graceful: crate::containment::windows::mechanism_from_flags(crate::containment::windows::group_flags()),
            #[cfg(windows)]
            frozen: false,
        };
        #[cfg(windows)]
        let proc_handle = {
            use std::os::windows::io::AsRawHandle;
            child.as_raw_handle()
        };
        let crate::identity::Resolved::Found(id) = crate::identity::ProcessId::of(child.id()) else {
            panic!("the helper child must be readable");
        };
        let attachment = attach(
            id,
            #[cfg(target_os = "linux")]
            crate::containment::cgroup::test_support::handle_of(
                child.id(),
                &crate::containment::cgroup::test_support::pidfd_of(child.id()),
            ),
            #[cfg(windows)]
            proc_handle,
            prepared,
        )
        .expect("attach nested");
        let (containment, attached) = (attachment.containment, attachment.attached);
        // Reap before asserting: `attached` is owned and independent of `child`, so a
        // failing assertion must not leak the helper (the nested arms don't touch it).
        _ = child.kill();
        _ = child.wait();
        assert_eq!(
            containment,
            Containment::Delegated,
            "nested member ({mode:?}) must report Containment::Delegated, got {containment:?}"
        );
        assert!(
            matches!(attached, Attached::Delegated),
            "nested member ({mode:?}) must be Attached::Delegated, got {attached:?}"
        );
    }
}

// kill_tree handle-backstop (treewalk / macOS fd-marker fault seam) =====

// A long-lived TreeWalk-contained child; no descendants, so with the root identity-kill
// seam-disabled the ONLY killer is kill_tree's handle backstop. Armed AFTER the fallible
// spawn so a spawn panic cannot leak the flag.
//
// On macOS, `ContainMode::TreeWalk` still attaches `Containment::FdMarker` (decision 2: the
// marker installs for every contained root regardless of requested mode) — its `sweep` calls
// `treewalk::kill_by_identity` directly, never `treewalk::hard_kill`, so `treewalk::fault`'s
// seam is never consumed there; `fdmarker::fault` provides the matching seam instead.
#[skuld::test]
fn sync_kill_tree_backstop_is_load_bearing() {
    #[cfg(not(target_os = "macos"))]
    use super::super::treewalk::fault;
    #[cfg(target_os = "macos")]
    use crate::containment::fdmarker::fault;
    let mut cmd = crate::Command::new();
    #[cfg(unix)]
    cmd.args(["cat"]);
    #[cfg(windows)]
    cmd.args([crate::test_child::windows_more()]);
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    #[cfg(windows)]
    cmd.stdout(crate::Stdio::null()).expect("set stdout null");
    cmd.contain_with(crate::ContainMode::TreeWalk);
    let mut child = cmd.spawn().expect("spawn");
    // Closed right after the kill: only a real kill can end the child before then, so a no-op
    // backstop exits 0 and fails the assertion instead of hanging `wait()`.
    let stdin = child.stdin().expect("piped stdin");
    fault::set_force_root_kill_noop(true);
    let result = child.kill_tree();
    assert!(
        !fault::armed(),
        "seam not consumed — hard_kill did not run on the arming thread"
    );
    result.expect("kill_tree via backstop");
    drop(stdin);
    let status = child.wait().expect("reap");
    assert!(
        !status.success(),
        "the handle backstop must be what killed the root, got {status:?}"
    );
}

#[cfg(feature = "tokio")]
#[skuld::test]
async fn async_kill_tree_backstop_is_load_bearing() {
    #[cfg(not(target_os = "macos"))]
    use super::super::treewalk::fault;
    #[cfg(target_os = "macos")]
    use crate::containment::fdmarker::fault;
    let mut cmd = crate::tokio::Command::new();
    #[cfg(unix)]
    cmd.args(["cat"]);
    #[cfg(windows)]
    cmd.args([crate::test_child::windows_more()]);
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    #[cfg(windows)]
    cmd.stdout(crate::Stdio::null()).expect("set stdout null");
    cmd.contain_with(crate::ContainMode::TreeWalk);
    let mut child = cmd.spawn().expect("spawn");
    // Closed right after the kill: only a real kill can end the child before then, so a no-op
    // backstop exits 0 and fails the assertion instead of hanging `wait()`.
    let stdin = child.stdin().expect("piped stdin");
    fault::set_force_root_kill_noop(true);
    let result = child.kill_tree();
    assert!(
        !fault::armed(),
        "seam not consumed — hard_kill did not run on the arming thread"
    );
    result.expect("kill_tree via backstop");
    drop(stdin);
    let status = child.wait().await.expect("reap");
    assert!(
        !status.success(),
        "the handle backstop must be what killed the root, got {status:?}"
    );
}

// fd marker install policy (macOS) =====

/// The install policy, exhaustively: every mode installs a marker for a ROOT spawn, no
/// nested spawn ever does (it inherits the root's), no uncontained spawn does, and an
/// elevation-derived spawn does not (its `sudo` wrapper closes every descriptor >= 3).
#[cfg(target_os = "macos")]
#[skuld::test]
fn marker_wanted_installs_for_every_contained_root_and_nothing_else() {
    use crate::containment::fdmarker::marker_wanted;
    use crate::containment::ContainMode;
    for mode in [ContainMode::Strongest, ContainMode::Session, ContainMode::TreeWalk] {
        assert!(
            marker_wanted(Some(mode), true, false),
            "{mode:?} root installs a marker"
        );
        assert!(
            !marker_wanted(Some(mode), false, false),
            "{mode:?} nested inherits, never installs"
        );
        assert!(
            !marker_wanted(Some(mode), true, true),
            "{mode:?} elevated root must not install"
        );
    }
    assert!(
        !marker_wanted(None, true, false),
        "an uncontained spawn installs no marker"
    );
}

/// The marker mechanism is actionable: `kill_tree`/`terminate_tree` act on it.
#[cfg(target_os = "macos")]
#[skuld::test]
fn attached_fd_marker_is_actionable() {
    use std::os::fd::{AsFd, AsRawFd};

    use super::Attached;
    let (read, write) = std::io::pipe().expect("pipe");
    let handle = crate::containment::fdmarker::pipe_handle_of(write.as_fd()).expect("handle");
    let read_handle = crate::containment::fdmarker::pipe_handle_of(read.as_fd()).expect("read handle");
    let prepared = crate::containment::fdmarker::PreparedMarker {
        read: std::os::fd::OwnedFd::from(read),
        handle,
        read_handle,
        fd: write.as_fd().as_raw_fd(),
    };
    let marker = crate::containment::fdmarker::Marker::new(
        prepared,
        crate::containment::fdmarker::fdmarker_tests::inert_root(),
        None,
    );
    assert!(Attached::FdMarker(marker).is_actionable());
}

/// `prepare` must thread the caller's reserved child fds through to the placement, or a user
/// fd mapping would dup2 over the marker in the child.
#[cfg(target_os = "macos")]
#[skuld::test]
fn prepare_places_the_marker_above_the_callers_reserved_fds() {
    use crate::containment::{ContainMode, ContainRequest, Nesting};
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let prepared = super::prepare(
        &mut cmd,
        &ContainRequest {
            mode: Some(ContainMode::Strongest),
            nesting: Nesting::Mark,
        },
        &crate::command::flags::FlagsRequest::default(),
        &[3, 4, 5, 6, 7, 8, 9, 10],
        false,
        &[],
    )
    .expect("prepare is infallible off Windows");
    let marker = prepared.marker.as_ref().expect("a contained macOS root gets a marker");
    assert!(
        marker.fd > 10,
        "prepare placed the marker on fd {}, which a user mapping would dup2 over",
        marker.fd
    );
}

/// A failed install degrades to the pre-existing mechanism rather than failing the spawn.
#[cfg(target_os = "macos")]
#[skuld::test]
fn a_failed_marker_install_leaves_prepare_without_one() {
    use crate::containment::fdmarker::fault::{lock_for_log_assertion, set_fault, Fault};
    use crate::containment::{ContainMode, ContainRequest, Nesting};
    // This test doesn't assert on log content itself, but triggering `Fault::Pipe` DOES emit
    // "fd marker: pipe() failed" into the shared `log_capture` buffer once any test has called
    // `log_capture::install()` — held for the whole body so it cannot land inside the sibling
    // fd-marker test module's fault-injection log-scanning test's scanned window on another
    // thread.
    let _serialize = lock_for_log_assertion();
    let mut cmd = std::process::Command::new("/usr/bin/true");
    set_fault(Some(Fault::Pipe));
    let prepared = super::prepare(
        &mut cmd,
        &ContainRequest {
            mode: Some(ContainMode::Strongest),
            nesting: Nesting::Mark,
        },
        &crate::command::flags::FlagsRequest::default(),
        &[],
        false,
        &[],
    )
    .expect("prepare is infallible off Windows");
    assert!(prepared.marker.is_none(), "the forced failure must yield no marker");
}

/// An elevation-derived spawn must not install a marker: `sudo` closes every descriptor >= 3.
#[cfg(target_os = "macos")]
#[skuld::test]
fn prepare_installs_no_marker_for_an_elevation_derived_spawn() {
    use crate::containment::{ContainMode, ContainRequest, Nesting};
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let prepared = super::prepare(
        &mut cmd,
        &ContainRequest {
            mode: Some(ContainMode::Strongest),
            nesting: Nesting::Mark,
        },
        &crate::command::flags::FlagsRequest::default(),
        &[],
        true,
        &[],
    )
    .expect("prepare is infallible off Windows");
    assert!(
        prepared.marker.is_none(),
        "an elevated spawn must not claim marker containment"
    );
}

/// The spawn's identity read tells an OS refusal from a vanished pid: denial must not read as
/// vanishing, and absence must not read as denial.
#[cfg(windows)]
#[skuld::test]
fn spawn_identity_distinguishes_a_denied_pid_from_a_vanished_one() {
    use crate::child::spawn::{resolve_identity_unchecked, spawn_identity_error};
    use windows::Win32::System::Threading::PROCESS_SYNCHRONIZE;
    let child = crate::identity::windows_fixture::spawn_restricted(PROCESS_SYNCHRONIZE.0);
    assert!(child.is_running(), "precondition: the subject must be live");

    let denied = spawn_identity_error(resolve_identity_unchecked(child.pid()));
    assert!(
        matches!(denied, crate::error::Error::Unassessable { .. }),
        "a pid we may not query must not read as vanished: {denied:?}"
    );

    // Contrast: a pid no process holds.
    let absent = spawn_identity_error(resolve_identity_unchecked(0xFFFF_FFF0));
    assert!(
        matches!(&absent, crate::error::Error::Io(e) if e.to_string().contains("reaped by another party")),
        "absence must not read as denial: {absent:?}"
    );
}

#[cfg(target_os = "macos")]
#[skuld::test]
fn wait_drained_is_unsupported_without_a_marker() {
    // Mirrors `require_contained`: a mechanism that cannot answer says so, rather than
    // implying a guarantee it has not got.
    use super::Attached;
    for attached in [Attached::None, Attached::Delegated] {
        let err = attached
            .wait_drained(Some(Some(std::time::Instant::now())))
            .expect_err("a mechanism with no drain edge must be Unsupported");
        assert!(matches!(err, crate::error::Error::Unsupported { .. }), "got {err:?}");
    }
}

#[cfg(target_os = "macos")]
#[skuld::test]
fn wait_drained_reports_members_remain_then_all_markers_closed() {
    use super::Attached;
    use crate::containment::fdmarker::{pipe_handle_of, Marker, PreparedMarker};
    use crate::containment::TreeDrain;
    use std::os::fd::{AsFd, OwnedFd};

    // A real holder in a separate process, mirroring marker_eof_tests.rs's
    // spawn_marker_holder: the marker's write end lives in the child, not in-process, so
    // wait_drained observes a genuinely open, then genuinely closed, write end.
    let mut cmd = crate::Command::new();
    cmd.executable("/bin/sh").args(["sh", "-c", "exec cat >/dev/null"]);
    cmd.fd(0, crate::Stdio::pipe_in()).expect("stdin pipe");
    cmd.fd(3, crate::Stdio::pipe_out()).expect("marker pipe");
    let mut child = cmd.spawn().expect("spawn /bin/sh");
    let marker = child.fd_read_end(3.into()).expect("marker read end");
    let stdin = child.fd_write_end(crate::Fd::STDIN).expect("stdin write end");

    // wait_drained now consults read_handle too (Marker::wait_drained calls
    // check_read_end_still_valid first, same as hard_kill/terminate) — so this uses the read
    // end's REAL current handle for both fields, standing in for install()'s full write-end
    // capture sequence without replicating it.
    let handle = pipe_handle_of(marker.as_fd()).expect("handle");
    let prepared = PreparedMarker {
        read: OwnedFd::from(marker),
        handle,
        read_handle: handle,
        fd: 3,
    };
    let attached = Attached::FdMarker(Marker::new(
        prepared,
        crate::containment::fdmarker::fdmarker_tests::inert_root(),
        None,
    ));

    assert_eq!(
        attached
            .wait_drained(Some(Some(std::time::Instant::now())))
            .expect("bounded wait while the holder is alive"),
        TreeDrain::MembersRemain
    );

    drop(stdin); // cat's stdin EOFs, so cat exits, closing its inherited marker write end
    child.wait().expect("reap");

    assert_eq!(
        attached
            .wait_drained(None)
            .expect("unbounded wait after the holder exits"),
        TreeDrain::AllMarkersClosed
    );
}

/// The UAC-elevated attachment bypasses `mechanism_from_flags` entirely — nothing in the flag
/// matrix covers it — so its three fields are pinned here. `Unknown`, not the `None` a flagless
/// spawn yields nor the `OtherConsoleGroup` a suppressed one does: a copy-paste of either must
/// fail. What the dispatcher then does with the value is
/// `signal_refuses_a_child_cosca_did_not_create`, in `src/graceful_tests.rs`.
#[cfg(windows)]
#[skuld::test]
fn uac_elevated_attachment_has_no_in_process_route() {
    use super::{Attached, Attachment};
    use crate::containment::Containment;
    use crate::graceful::GracefulMechanism;

    let a = Attachment::uac_elevated();
    assert_eq!(a.containment, Containment::None);
    assert!(matches!(a.attached, Attached::None), "got {:?}", a.attached);
    assert_eq!(a.graceful, GracefulMechanism::Unknown);
}

// The cgroup placement decision =====
// `attach_tree` decides whether a Strongest root's leaf owns its tree. The child's own
// self-placement report is the oracle: a later `cgroup.procs` read lists only LIVE tasks, so a
// placed child that has already exited reads back as absent. Real filesystem, no cgroupfs: each
// leaf is a temp directory shaped with ordinary files. These tests are about what the decision
// does with a report, not how a child earns one: a failed write is made for real, in-process,
// but `Placed` is stored directly, since a successful write to anything but a real `cgroup.procs`
// is the very false report the live cgroup lane guards against.

/// What the child's `pre_exec` closure reported, if it ran at all.
#[cfg(target_os = "linux")]
#[derive(Clone, Copy)]
enum ChildReport {
    Placed,
    WriteFailed,
    NotReported,
}

/// Run the decision for a leaf at `leaf_path` whose child reported `report`.
#[cfg(target_os = "linux")]
fn decide(leaf_path: &std::path::Path, report: ChildReport) -> (crate::containment::Containment, super::Attached) {
    use crate::containment::cgroup::{place_self_in_cgroup_pre_exec, CgroupLeaf};

    let leaf = CgroupLeaf::for_test_at(leaf_path.to_path_buf());
    match report {
        // SAFETY: the slot's pipe lives as long as `leaf`.
        ChildReport::Placed => unsafe { leaf.placement_slot().report_placed_for_test() },
        ChildReport::WriteFailed => {
            // SAFETY: fd -1 is never writable, so the write fails with EBADF; closing -1 is a
            // no-op. The slot's pipe lives as long as `leaf`.
            _ = unsafe { place_self_in_cgroup_pre_exec(-1, leaf.placement_slot()) };
        }
        ChildReport::NotReported => {}
    }
    let prepared = super::Prepared {
        mode: Some(crate::containment::ContainMode::Strongest),
        is_root: true,
        cgroup_leaf: Some(leaf),
    };
    super::attach_tree(
        crate::identity::ProcessId::current(),
        crate::containment::cgroup::test_support::handle_of(
            std::process::id(),
            &crate::containment::cgroup::test_support::pidfd_of(std::process::id()),
        ),
        prepared,
    )
    .expect("attach_tree")
}

/// A leaf directory whose `cgroup.procs` lists some OTHER pid, never this test's.
#[cfg(target_os = "linux")]
fn leaf_listing_another_pid(dir: &std::path::Path) -> std::path::PathBuf {
    let leaf_path = dir.join("cosca-decision-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let other = std::process::id().wrapping_add(1);
    std::fs::write(leaf_path.join("cgroup.procs"), format!("{other}\n")).expect("write cgroup.procs");
    leaf_path
}

/// A child that reported its write accepted, and has since exited: `cgroup.procs` no longer
/// lists it. Anything it forked is still in the leaf, so the leaf owns the tree.
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn a_placed_report_outranks_a_cgroup_procs_that_omits_the_child() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = leaf_listing_another_pid(dir.path());

    let (containment, attached) = decide(&leaf_path, ChildReport::Placed);

    assert_eq!(containment, crate::containment::Containment::CgroupV2);
    let super::Attached::Cgroup(leaf) = &attached else {
        panic!("got {attached:?}");
    };
    assert!(
        !leaf.holds_spawn_resources(),
        "a live child's leaf must not hold its cgroup.procs fd or report pipe past the verdict"
    );
    assert!(
        !leaf_path.join("cgroup.kill").exists(),
        "the leaf owns a live tree; nothing may kill it at spawn time"
    );
}

/// Membership that cannot be read is unknown, not absent — and the child's own report already
/// answers it.
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn a_placed_report_outranks_an_unreadable_cgroup_procs() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-decision-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf (no cgroup.procs inside)");

    let (containment, attached) = decide(&leaf_path, ChildReport::Placed);

    assert_eq!(containment, crate::containment::Containment::CgroupV2);
    assert!(matches!(attached, super::Attached::Cgroup(_)), "got {attached:?}");
}

/// A child whose write failed never entered the leaf, so neither did anything it forked: the
/// spawn degrades and the empty leaf is removed.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_write_degrades_and_removes_the_leaf() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-decision-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf");

    let (containment, attached) = decide(&leaf_path, ChildReport::WriteFailed);

    assert_eq!(containment, crate::containment::Containment::ProcessGroup);
    assert!(matches!(attached, super::Attached::ProcessGroup(_)), "got {attached:?}");
    assert!(!leaf_path.exists(), "the degrade must remove the leaf it created");
}

/// Removing a leaf the child never entered must never write `cgroup.kill`, even when the leaf
/// will not go away: whatever is in it, cosca did not put there. The leaf left behind is
/// reported.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_degrade_never_kills_through_the_leaf() {
    crate::log_capture::install();
    for report in [ChildReport::WriteFailed, ChildReport::NotReported] {
        let dir = tempfile::tempdir().expect("tempdir");
        // A `cgroup.procs` file makes the directory non-empty, so its `rmdir` fails.
        let leaf_path = leaf_listing_another_pid(dir.path());

        let mark = crate::log_capture::mark();
        let (containment, _attached) = decide(&leaf_path, report);

        assert_eq!(containment, crate::containment::Containment::ProcessGroup);
        assert!(
            !leaf_path.join("cgroup.kill").exists(),
            "a degrade wrote cgroup.kill: it would kill a tree cosca had just been asked to contain"
        );
        let left_behind: Vec<String> = crate::log_capture::records_since(mark, &leaf_path.to_string_lossy())
            .into_iter()
            .filter(|record| record.contains("was not removed"))
            .collect();
        assert_eq!(
            left_behind.len(),
            1,
            "the unremoved leaf is reported once: {left_behind:?}"
        );
    }
}

// kill_on_drop's reach into the containment resource =====
// See `Attached::honor_kill_on_drop`.

/// A leaf standing in for a live contained tree: occupied (so `rmdir` fails and `Drop` would
/// reach for `cgroup.kill`) and carrying an empty `cgroup.kill` to read the write back from.
#[cfg(target_os = "linux")]
fn occupied_leaf_for_test(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
    let leaf_path = dir.join(name);
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    std::fs::write(leaf_path.join("occupant"), "").expect("stand in for the live tree");
    std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");
    leaf_path
}

#[cfg(target_os = "linux")]
fn cgroup_attachment_for_test(leaf_path: &std::path::Path) -> super::Attachment {
    super::Attachment {
        containment: crate::containment::Containment::CgroupV2,
        attached: super::Attached::Cgroup(crate::containment::cgroup::test_support::entered_leaf_at(
            leaf_path.to_path_buf(),
        )),
        graceful: crate::graceful::GracefulMechanism::Process,
    }
}

/// `kill_on_drop(false)` must disarm the cgroup leaf. Without it the handle's own teardown is
/// skipped and the leaf's `Drop` kills the tree anyway — the opposite of the opt-out.
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn kill_on_drop_false_disarms_a_cgroup_leaf() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = occupied_leaf_for_test(dir.path(), "cosca-kill-on-drop-false-leaf");

    let attachment = cgroup_attachment_for_test(&leaf_path);
    attachment.attached.honor_kill_on_drop(false);
    drop(attachment);

    assert_eq!(
        std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
        b"",
        "kill_on_drop(false) opts out of the teardown; a tree it killed anyway is the opposite"
    );
}

/// The same leaf under `kill_on_drop(true)` DOES fire `cgroup.kill`, so the test above pins
/// the disarm rather than an inert path.
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn kill_on_drop_true_leaves_a_cgroup_leaf_armed() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = occupied_leaf_for_test(dir.path(), "cosca-kill-on-drop-true-leaf");

    let attachment = cgroup_attachment_for_test(&leaf_path);
    attachment.attached.honor_kill_on_drop(true);
    drop(attachment);

    assert_eq!(
        std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
        b"1",
        "the default is still a kill-on-drop teardown"
    );
}

// ===== frozen attach (Windows) =====

#[cfg(windows)]
mod frozen_attach {
    use crate::containment::dispatch::{attach, Attached, Attachment, Prepared};
    use crate::containment::windows::fault::{force_next, Step};
    use crate::containment::{ContainMode, Containment};
    use crate::error::Error;
    use crate::test_frozen::{raw, spawn_suspended_blocker, InitialThread};

    const ERROR_ACCESS_DENIED: u32 = 5;

    fn prepared(mode: Option<ContainMode>, is_root: bool, frozen: bool) -> Prepared {
        Prepared {
            mode,
            is_root,
            graceful: crate::graceful::GracefulMechanism::None,
            frozen,
        }
    }

    fn attach_suspended(child: &std::process::Child, prepared: Prepared) -> Result<Attachment, Error> {
        let crate::identity::Resolved::Found(id) = crate::identity::ProcessId::of(child.id()) else {
            panic!("the suspended child must be readable");
        };
        attach(id, raw(child), prepared)
    }

    fn dispose(mut child: std::process::Child) {
        child.kill().expect("kill the test child");
        child.wait().expect("reap the test child");
    }

    /// A frozen Strongest root is assigned its containment job and stays suspended.
    #[skuld::test]
    fn death_watch_attach_frozen_assigns_a_strongest_roots_job_and_leaves_the_thread_suspended() {
        let child = spawn_suspended_blocker();
        let thread = InitialThread::of(child.id());

        let attachment = attach_suspended(&child, prepared(Some(ContainMode::Strongest), true, true)).expect("attach");

        assert_eq!(attachment.containment, Containment::JobObject);
        assert!(matches!(attachment.attached, Attached::JobObject(_)));
        assert_eq!(thread.suspend_count(), 1, "a frozen attach must not resume");
        drop(attachment);
        child
            .wait_with_output()
            .expect("the job's close killed the frozen child");
    }

    /// A frozen root needs its job to be held, so a failed assignment fails the attach instead of
    /// falling back to `TreeWalk`, which would leave nothing to kill it.
    #[skuld::test]
    fn attach_frozen_fails_when_the_strongest_assignment_fails_instead_of_falling_back_to_treewalk() {
        let child = spawn_suspended_blocker();
        let _forced = force_next(Step::Assign, ERROR_ACCESS_DENIED);

        let err = attach_suspended(&child, prepared(Some(ContainMode::Strongest), true, true))
            .err()
            .expect("a frozen attach with no job must fail");

        assert!(matches!(err, Error::Containment { .. }), "got {err:?}");
        dispose(child);
    }

    /// The ordinary attach is unchanged: it resumes, and a failed assignment still degrades to
    /// `TreeWalk`.
    #[skuld::test]
    fn attach_without_hold_still_resumes_and_still_falls_back_to_treewalk() {
        let child = spawn_suspended_blocker();
        let thread = InitialThread::of(child.id());
        let _forced = force_next(Step::Assign, ERROR_ACCESS_DENIED);

        let attachment = attach_suspended(&child, prepared(Some(ContainMode::Strongest), true, false)).expect("attach");

        assert_eq!(attachment.containment, Containment::TreeWalk);
        assert_eq!(thread.suspend_count(), 0, "the ordinary attach resumes the child");
        dispose(child);
    }

    /// Every shape without a cosca job of its own (`TreeWalk` root, nested member, uncontained) is
    /// left frozen and unjobbed: `attach` adds no job and keeps the containment it would report if
    /// the child were not frozen.
    #[skuld::test]
    fn attach_frozen_gives_treewalk_nested_and_uncontained_shapes_no_job_and_leaves_them_suspended() {
        let shapes = [
            (
                "treewalk root",
                Some(ContainMode::TreeWalk),
                true,
                Containment::TreeWalk,
            ),
            (
                "nested strongest member",
                Some(ContainMode::Strongest),
                false,
                Containment::Delegated,
            ),
            (
                "nested treewalk member",
                Some(ContainMode::TreeWalk),
                false,
                Containment::Delegated,
            ),
            ("uncontained", None, false, Containment::None),
        ];
        for (name, mode, is_root, expected) in shapes {
            let child = spawn_suspended_blocker();
            let thread = InitialThread::of(child.id());

            let attachment = attach_suspended(&child, prepared(mode, is_root, true)).expect(name);

            assert_eq!(attachment.containment, expected, "{name}");
            assert!(
                !matches!(attachment.attached, Attached::JobObject(_)),
                "{name}: no job of its own"
            );
            assert_eq!(thread.suspend_count(), 1, "{name}: a frozen attach must not resume");
            drop(attachment);
            dispose(child);
        }
    }
}