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
//! Unit tests for the macOS marker EOF edge. In the library because the primitive is
//! `pub(crate)`. Nothing here sleeps: every "the tree drained" event is caused by closing a
//! descriptor a child is blocked on, and every "the tree has not drained" assertion is a
//! ZERO-deadline check, which is exact rather than timed. The deadline contract and no-spin
//! claim get their own tests, in `deadline` — see that module's own doc.
//!
//! Every test that opens a `marker_pipe()` write end holds `test_spawn_lock()` for its WHOLE
//! body, whether or not that test itself spawns — the same rule `fdmarker_tests.rs` documents:
//! a sibling test's `fork()` elsewhere in this shared, parallel test binary can land while THIS
//! test's write end happens to be open, transiently inheriting a duplicate into a not-yet-`exec`ed
//! child (CLOEXEC only closes it AT exec, not at fork), which then reads as an extra holder and
//! delays the EOF this module exists to detect. `test_spawn_lock()` is `spawn_lock()` itself, not
//! a private mutex, because `crate::Command::spawn()` already takes it on macOS around its own
//! fork+exec — reusing it serializes against every cosca-originated spawn in this binary, not
//! just the ones in this file.

use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::time::{Duration, Instant};

use super::{arm, block_until_drained, drain_kqueue, probe, DrainOutcome};
use crate::containment::TreeDrain;

fn test_spawn_lock() -> crate::child::spawn::SpawnLockGuard {
    crate::child::spawn::spawn_lock()
}

/// A marker pipe: `(read_end, write_end)`, both owned by this process. Built with
/// `std::io::pipe()` (CLOEXEC by default, matching `fdmarker::create_pipe`'s own convention) —
/// NOT `nix::unistd::pipe()` (raw POSIX semantics, not CLOEXEC) — because when trials overlap
/// in one process (`--nocapture` with `--test-threads` > 1), a non-CLOEXEC test pipe fd would be inherited by any
/// OTHER concurrently-running test's spawned child, keeping that child a spurious extra "holder"
/// of a pipe this test never intended to share.
fn marker_pipe() -> (OwnedFd, OwnedFd) {
    let (r, w) = std::io::pipe().expect("pipe");
    (OwnedFd::from(r), OwnedFd::from(w))
}

/// A fd number NEVER allocated in this process: using it instead of a real,
/// just-closed fd means these tests cannot race a concurrently-running test that reuses a
/// freed number, and its errno (EBADF) was independently reproduced multiple times, unlike a
/// freshly-closed-then-reused fd's (EINVAL — a different, not-useful-here path).
fn never_allocated_fd() -> BorrowedFd<'static> {
    // SAFETY: this fd number is never used for I/O by this process (nothing opens a million
    // descriptors in a unit test), so it stays unallocated for the lifetime of the borrow;
    // every call through it is expected to fail with EBADF, which is exactly what's tested.
    unsafe { BorrowedFd::borrow_raw(1_000_000) }
}

/// A live tree member: `/bin/sh` holding the marker on fd 3 and blocked on stdin, so a test
/// ends it by closing a descriptor rather than by timing anything. Returns the owned child,
/// the marker read end, and the stdin write end whose close makes it exit.
///
/// Deliberately used even by tests below that just want "the write end is open, held by
/// SOMETHING that isn't me": once `refuse_if_write_end_held` is added to `arm`, a bare second
/// in-process fd (as plain `marker_pipe()` would give) is indistinguishable from the exact
/// supervisor bug the guard exists to catch, and would make `arm`/`probe` refuse rather
/// than report `MembersRemain`. A real holder in ANOTHER process is what "the write end is
/// open" is supposed to mean here.
fn spawn_marker_holder(script: &str) -> (crate::Child, std::io::PipeReader, std::io::PipeWriter) {
    let mut cmd = crate::Command::new();
    cmd.executable("/bin/sh").args(["sh", "-c", script]);
    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");
    (child, marker, stdin)
}

/// The `FIONREAD` ioctl: how many bytes are currently buffered and unread on `fd`. Exact,
/// kernel-reported — used to prove a drain did or did not happen, rather than inferring it
/// from a verdict that reports the same thing (`MembersRemain`) either way.
fn fionread(fd: BorrowedFd<'_>) -> i32 {
    let n = rustix::io::ioctl_fionread(fd).unwrap_or_else(|e| panic!("FIONREAD ioctl failed: {e}"));
    i32::try_from(n).expect("a pipe's buffered byte count fits an i32")
}

#[path = "marker_eof_tests/deadline.rs"]
mod deadline;

#[skuld::test]
fn probe_reports_drained_when_the_last_write_end_is_gone() {
    let _serialize = test_spawn_lock();
    let (r, w) = marker_pipe();
    drop(w); // the last holder's descriptor closed
    assert_eq!(probe(r.as_fd()).expect("probe"), TreeDrain::AllMarkersClosed);
}

#[skuld::test]
fn probe_reports_drained_even_with_bytes_still_buffered() {
    // kqueue(2): EV_EOF is set once the write end is closed even with data pending — checked
    // and returned before any read happens (`interpret_read_event`'s EV_EOF branch), so this
    // does NOT exercise `drain_pending`'s discard path (that needs bytes past the NOTE_LOWAT
    // clamp). What this pins: bytes must never change the verdict — the marker pipe is not a
    // data channel — regardless of which branch produces it.
    let _serialize = test_spawn_lock();
    let (r, w) = marker_pipe();
    nix::unistd::write(&w, b"noise from a member").expect("write");
    drop(w);
    assert_eq!(probe(r.as_fd()).expect("probe"), TreeDrain::AllMarkersClosed);
}

#[skuld::test]
fn drain_kqueue_reports_spurious_for_an_armed_empty_pipe() {
    // Nothing is pending, so `interpret_read_event` never runs.
    let (_child, marker, _stdin) = spawn_marker_holder("exec cat >/dev/null");
    let kq = arm(marker.as_fd(), false).expect("arm");
    let outcome = drain_kqueue(&kq, marker.as_fd(), true).expect("drain_kqueue");
    assert!(
        matches!(outcome, DrainOutcome::Spurious),
        "an empty pipe with a live holder must be Spurious, got {outcome:?}"
    );
}

#[skuld::test]
fn drain_kqueue_reports_declined_for_a_full_pipe_and_leaves_its_bytes() {
    let (marker_r, marker_w) = std::io::pipe().expect("pipe");
    let queued = fill_pipe_to_capacity(marker_r.as_fd(), marker_w.as_fd());
    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::from_file(std::fs::File::from(OwnedFd::from(marker_w))))
        .expect("marker pipe");
    let child = cmd.spawn().expect("spawn /bin/sh");

    let kq = arm(marker_r.as_fd(), false).expect("arm");
    let outcome = drain_kqueue(&kq, marker_r.as_fd(), true).expect("drain_kqueue");
    assert!(
        matches!(outcome, DrainOutcome::Declined),
        "a full pipe with a live holder must be Declined, got {outcome:?}"
    );
    assert_eq!(
        fionread(marker_r.as_fd()),
        queued,
        "suppress_drain=true must leave the bytes buffered"
    );

    // Killed through the `Child` handle before it is reaped (`docs/principles.md` §10).
    child.kill().expect("kill the holder");
    child.wait().expect("reap");
}

#[skuld::test]
fn drain_kqueue_reports_drained_once_the_write_end_is_closed() {
    let (child, marker, stdin) = spawn_marker_holder("exec cat >/dev/null");
    let kq = arm(marker.as_fd(), false).expect("arm");
    drop(stdin); // cat exits, closing the last write end
    child.wait().expect("reap");
    let outcome = drain_kqueue(&kq, marker.as_fd(), true).expect("drain_kqueue");
    assert!(
        matches!(outcome, DrainOutcome::Drained(TreeDrain::AllMarkersClosed)),
        "a closed write end must be Drained, got {outcome:?}"
    );
}

#[skuld::test]
fn probe_reports_members_remain_while_the_write_end_is_open() {
    let (_child, marker, _stdin) = spawn_marker_holder("exec cat >/dev/null");
    assert_eq!(probe(marker.as_fd()).expect("probe"), TreeDrain::MembersRemain);
}

#[skuld::test]
fn probe_on_an_invalid_descriptor_reports_an_io_error() {
    // A borrowed fd the caller passed after it was already invalid must fail loudly, never
    // silently report a verdict.
    let err = probe(never_allocated_fd()).expect_err("an invalid descriptor must error");
    assert!(
        matches!(err, crate::error::Error::Io(_)),
        "expected Error::Io, got {err:?}"
    );
}

#[skuld::test]
fn block_until_drained_with_a_past_deadline_behaves_like_a_one_shot_probe() {
    let (child, marker, stdin) = spawn_marker_holder("exec cat >/dev/null");
    assert_eq!(
        block_until_drained(marker.as_fd(), Some(Some(Instant::now()))).expect("probe"),
        TreeDrain::MembersRemain
    );
    drop(stdin);
    assert_eq!(
        block_until_drained(marker.as_fd(), None).expect("unbounded wait"),
        TreeDrain::AllMarkersClosed
    );
    child.wait().expect("reap");
}

#[skuld::test]
fn block_until_drained_with_a_past_deadline_still_reports_an_already_drained_tree() {
    // The equivalence the test above cannot pin: there the true state at the deadline is
    // `MembersRemain`, so a buggy short-circuit that returns `MembersRemain` without ever
    // consulting the kqueue would pass it too. Here the tree has ALREADY, GENUINELY drained
    // before the (already past) deadline is even passed in, so only a real check of the
    // sticky, level-triggered `EV_EOF` — not an assumption keyed on "deadline elapsed" — can
    // produce the right verdict.
    let _serialize = test_spawn_lock();
    let (r, w) = marker_pipe();
    let already_past = Instant::now();
    drop(w); // drained before the deadline below is even evaluated
    assert_eq!(
        block_until_drained(r.as_fd(), Some(Some(already_past))).expect("probe"),
        TreeDrain::AllMarkersClosed,
        "an already-drained tree must be reported as drained even past a stale deadline"
    );
}

#[skuld::test]
fn arm_on_an_invalid_descriptor_reports_an_io_error() {
    // Exercises `ensure_nonblocking`'s guard inside `arm` — the actual reachable failure mode
    // for a bad descriptor. `add_with_receipt`'s own EV_ERROR branch (for EVFILT_READ,
    // via `arm`) has no test anywhere in this module: a descriptor that passes
    // `ensure_nonblocking`'s fcntl check yet still fails kqueue's EV_ADD is not something this
    // module found a reliable, portable way to construct.
    let err = super::arm(never_allocated_fd(), false).expect_err("arming an invalid descriptor must error");
    assert!(
        matches!(err, crate::error::Error::Io(_)),
        "expected Error::Io, got {err:?}"
    );
}

#[skuld::test]
fn a_retained_supervisor_write_end_is_refused_not_waited_on() {
    // Measured: with the supervisor's own copy of the write end open, the edge NEVER fires
    // though every member exited. A wait here could only ever burn the caller's deadline, so
    // the primitive must refuse instead of pretending to watch.
    let _serialize = test_spawn_lock();
    let (r, w) = marker_pipe();
    assert_eq!(super::write_end_check(r.as_fd()), super::WriteEndCheck::HeldByUs);
    let err = probe(r.as_fd()).expect_err("a retained write end must be refused");
    assert!(
        matches!(err, crate::error::Error::Containment { .. }),
        "expected Error::Containment, got {err:?}"
    );
    drop(w);
    // NOT `assert_eq!(..., Clear)`: when trials overlap (see `marker_pipe`'s doc), this
    // process's fd table is being churned by every other running test. The
    // property under test is that a CLEARED write end is never mistaken for a still-held one.
    assert_ne!(super::write_end_check(r.as_fd()), super::WriteEndCheck::HeldByUs);
    assert_eq!(probe(r.as_fd()).expect("probe"), TreeDrain::AllMarkersClosed);
}

#[skuld::test]
fn write_end_check_ignores_unrelated_pipes_this_process_holds() {
    // The check must key on the marker's own kernel object, not on "this process holds some
    // pipe write end" — a supervisor holds many (every child's stdin). Same concurrency note
    // as above: assert the property (not HeldByUs), not an exact Clear.
    let _serialize = test_spawn_lock();
    let (r, w) = marker_pipe();
    let (_other_r, _other_w) = marker_pipe();
    drop(w);
    assert_ne!(super::write_end_check(r.as_fd()), super::WriteEndCheck::HeldByUs);
}

#[skuld::test]
fn write_end_check_is_unassessable_for_a_descriptor_that_is_not_a_pipe() {
    // proc_pidfdinfo(PROC_PIDFDPIPEINFO) on a non-pipe fd fails (wrong type) — the check must
    // say "inconclusive", never misreport it as Clear (which `probe`/`arm` would then trust).
    let f = std::fs::File::open("/dev/null").expect("open /dev/null");
    assert_eq!(super::write_end_check(f.as_fd()), super::WriteEndCheck::Unassessable);
}

#[skuld::test]
fn an_unassessable_write_end_check_refuses_only_an_unbounded_wait() {
    // `Unassessable` is not evidence of a bug (an ordinary transient
    // scan gap under concurrent spawning), so a BOUNDED wait proceeds — its own deadline
    // already caps the exposure. Only an UNBOUNDED wait is refused, because that combination
    // is exactly the condition under which the primitive could otherwise hang forever with no
    // elevated runtime signal at all.
    let f = std::fs::File::open("/dev/null").expect("open /dev/null");
    assert_eq!(super::write_end_check(f.as_fd()), super::WriteEndCheck::Unassessable);
    // Bounded (a real, already-past deadline): proceeds past the write-end guard, then fails
    // for the ordinary reason (not a pipe, so `EVFILT_READ` cannot be armed on it) — never
    // `Error::Unassessable`.
    let bounded = block_until_drained(f.as_fd(), Some(Some(Instant::now())));
    assert!(
        !matches!(bounded, Err(crate::error::Error::Unassessable { .. })),
        "a bounded wait must not be refused on an Unassessable write-end check, got {bounded:?}"
    );
    // Unbounded: refused outright.
    let unbounded = block_until_drained(f.as_fd(), None);
    assert!(
        matches!(unbounded, Err(crate::error::Error::Unassessable { .. })),
        "an unbounded wait must be refused on an Unassessable write-end check, got {unbounded:?}"
    );
}

#[skuld::test]
fn a_live_member_holds_the_edge_shut_and_releases_it_on_exit() {
    // `cat` blocks on stdin and holds the inherited fd 3; closing our stdin write end is the
    // only thing that ends it, so the drain is caused by an event, never awaited on a clock.
    let (child, marker, stdin) = spawn_marker_holder("exec cat >/dev/null");
    assert_eq!(
        block_until_drained(marker.as_fd(), Some(Some(Instant::now()))).expect("probe"),
        TreeDrain::MembersRemain,
        "a live marker holder must hold the edge shut"
    );
    drop(stdin); // cat sees EOF on stdin and exits
    assert_eq!(
        block_until_drained(marker.as_fd(), None).expect("unbounded wait"),
        TreeDrain::AllMarkersClosed
    );
    child.wait().expect("reap");
}

#[skuld::test]
fn the_edge_is_sticky_for_a_waiter_that_arrives_late() {
    // kqueue EVFILT_READ is level-triggered on a pipe: a kqueue armed after the drain
    // reports EV_EOF immediately, so a late waiter can never miss the edge.
    let (child, marker, stdin) = spawn_marker_holder("exec cat >/dev/null");
    drop(stdin);
    child.wait().expect("reap");
    assert_eq!(
        block_until_drained(marker.as_fd(), None).expect("late wait"),
        TreeDrain::AllMarkersClosed
    );
}

#[skuld::test]
fn a_member_that_closes_the_marker_leaves_the_set_early() {
    // The documented limit, pinned as behaviour rather than prose: `exec 3>&-` drops the
    // descriptor, so the edge fires while the member is demonstrably still running.
    let (child, marker, stdin) = spawn_marker_holder("exec 3>&-; exec cat >/dev/null");
    assert_eq!(
        block_until_drained(marker.as_fd(), None).expect("wait"),
        TreeDrain::AllMarkersClosed,
        "a member that closed the marker must leave the membership set"
    );
    assert_eq!(
        child.is_alive(),
        crate::identity::Liveness::Alive,
        "the false edge is only meaningful if the member is still running"
    );
    drop(stdin);
    child.wait().expect("reap");
}

#[skuld::test]
fn an_orphan_reparented_to_launchd_holds_the_edge_shut() {
    // The population no other mechanism on this platform can see. `sh` backgrounds `cat`,
    // reports its pid on fd 4 and exits, so `cat` is reparented to launchd (ppid == 1) while
    // still holding the inherited marker on fd 3 across `sh`'s own exec.
    //
    // `cat` needs an EXPLICIT stdin redirect (`0<&0`) even though it is already fd 0 as
    // inherited: macOS `/bin/sh` (bash 3.2.57) redirects a backgrounded job's stdin to
    // /dev/null when the job has no redirection of its OWN and job control is off (the
    // normal state for a non-interactive `-c` script) — without `0<&0`, this exact fd
    // plumbing produces a `cat` that reads immediate EOF and exits, never becoming the
    // long-lived orphan the test needs; WITH it, the orphan survives and holds the marker.
    let mut cmd = crate::Command::new();
    cmd.executable("/bin/sh")
        .args(["sh", "-c", "cat 0<&0 >/dev/null & echo $! >&4"]);
    cmd.fd(0, crate::Stdio::pipe_in()).expect("stdin pipe");
    cmd.fd(3, crate::Stdio::pipe_out()).expect("marker pipe");
    cmd.fd(4, crate::Stdio::pipe_out()).expect("report pipe");
    let mut child = cmd.spawn().expect("spawn /bin/sh");
    let marker = child.fd_read_end(3.into()).expect("marker read end");
    let report = child.fd_read_end(4.into()).expect("report read end");
    let stdin = child.fd_write_end(crate::Fd::STDIN).expect("stdin write end");

    let orphan_pid: u32 = {
        use std::io::BufRead;
        let mut line = String::new();
        std::io::BufReader::new(report).read_line(&mut line).expect("read pid");
        line.trim().parse().expect("pid")
    };
    child.wait().expect("the root sh exits once it has backgrounded cat");

    // The root is reaped; the only marker holder left is the orphan.
    let parents = crate::containment::enumerate::process_parents().expect("the process snapshot");
    let ppid = parents
        .iter()
        .find(|(pid, _)| *pid == orphan_pid)
        .map(|(_, ppid)| *ppid)
        .expect("the orphan is in the process table");
    assert_eq!(ppid, 1, "the orphan must be reparented to launchd");

    assert_eq!(
        block_until_drained(marker.as_fd(), Some(Some(Instant::now()))).expect("probe"),
        TreeDrain::MembersRemain,
        "an orphan at ppid=1 must hold the edge shut after the root is gone"
    );

    drop(stdin); // the orphan's only exit path — no signal, no timer
    assert_eq!(
        block_until_drained(marker.as_fd(), None).expect("unbounded wait"),
        TreeDrain::AllMarkersClosed,
        "the edge must fire when the orphan exits"
    );
}

#[skuld::test]
fn all_markers_closed_requires_every_simultaneous_holder_to_exit() {
    // Every test above this one has exactly ONE write-end holder at a time, so none of them can
    // tell "some closed" from "all closed" apart — a bug that reported `AllMarkersClosed` the
    // moment ANY single holder's copy closed, ignoring the rest, would still pass every one of
    // them. This test needs two INDEPENDENTLY closable holders alive at once: a single root
    // `/bin/sh` backgrounds two separate `cat` processes, each with its OWN stdin pipe (fd 0
    // and fd 5) so each can be closed on its own, both inheriting the same fd 3 from the one
    // spawn. The root closes its own fd 3 copy right after backgrounding (`exec 3>&-`) so it is
    // never itself a third holder, then `wait`s for both children instead of exiting — nothing
    // here depends on reparenting, unlike the orphan test above.
    let mut cmd = crate::Command::new();
    cmd.executable("/bin/sh").args([
        "sh",
        "-c",
        "cat 0<&0 >/dev/null & cat 0<&5 >/dev/null & exec 3>&-; wait",
    ]);
    cmd.fd(0, crate::Stdio::pipe_in()).expect("stdin pipe for holder A");
    cmd.fd(3, crate::Stdio::pipe_out()).expect("marker pipe");
    cmd.fd(5, crate::Stdio::pipe_in()).expect("stdin pipe for holder B");
    let mut child = cmd.spawn().expect("spawn /bin/sh");
    let marker = child.fd_read_end(3.into()).expect("marker read end");
    let stdin_a = child.fd_write_end(crate::Fd::STDIN).expect("holder A stdin write end");
    let stdin_b = child.fd_write_end(5.into()).expect("holder B stdin write end");

    assert_eq!(
        block_until_drained(marker.as_fd(), Some(Some(Instant::now()))).expect("probe"),
        TreeDrain::MembersRemain,
        "two live holders must hold the edge shut"
    );

    drop(stdin_a); // holder A sees EOF on its own stdin and exits; holder B is untouched
    assert_eq!(
        block_until_drained(marker.as_fd(), Some(Some(Instant::now()))).expect("probe"),
        TreeDrain::MembersRemain,
        "one holder exiting while a second remains must not be mistaken for a full drain"
    );

    drop(stdin_b); // holder B sees EOF and exits; no holder remains
    assert_eq!(
        block_until_drained(marker.as_fd(), None).expect("unbounded wait"),
        TreeDrain::AllMarkersClosed,
        "the edge must fire only once the LAST simultaneous holder is gone"
    );
    child
        .wait()
        .expect("reap the root sh, which itself waited for both background cats");
}

#[skuld::test]
fn small_bytes_from_a_member_are_not_a_drain() {
    // The verdict-level half of the NOTE_LOWAT claim: a handful of buffered bytes must never
    // read as a drain, gated or not (`interpret_read_event`'s non-EOF branch reports
    // `MembersRemain` either way). The ZERO-deadline check is the exact, correct tool here
    // (matching this file's own header promise), not a multi-second real wait. Whether the
    // wakeup itself is actually suppressed is a SEPARATE, lower-level claim, pinned by the
    // low-water suppression test below (a verdict-only assertion cannot distinguish
    // "suppressed" from "delivered but harmless"). The child
    // signals readiness on a SEPARATE report pipe right after writing to fd 3, so the ordering
    // ("the write already happened") is real synchronization, not assumed.
    let mut cmd = crate::Command::new();
    cmd.executable("/bin/sh")
        .args(["sh", "-c", "echo noise >&3; echo ready >&4; exec cat >/dev/null"]);
    cmd.fd(0, crate::Stdio::pipe_in()).expect("stdin pipe");
    cmd.fd(3, crate::Stdio::pipe_out()).expect("marker pipe");
    cmd.fd(4, crate::Stdio::pipe_out()).expect("report pipe");
    let mut child = cmd.spawn().expect("spawn /bin/sh");
    let marker = child.fd_read_end(3.into()).expect("marker read end");
    let mut report = child.fd_read_end(4.into()).expect("report read end");
    let stdin = child.fd_write_end(crate::Fd::STDIN).expect("stdin write end");

    use std::io::Read;
    let mut byte = [0u8; 1];
    report
        .read_exact(&mut byte)
        .expect("the child wrote to fd 3 before this returns");

    assert_eq!(
        block_until_drained(marker.as_fd(), Some(Some(Instant::now()))).expect("zero-deadline check"),
        TreeDrain::MembersRemain,
        "a handful of buffered bytes under the low-water clamp must not be mistaken for a drain"
    );
    drop(stdin);
    assert_eq!(
        block_until_drained(marker.as_fd(), None).expect("unbounded wait"),
        TreeDrain::AllMarkersClosed
    );
    child.wait().expect("reap");
}

#[skuld::test]
fn note_lowat_suppresses_a_wakeup_for_bytes_under_the_clamp() {
    // The lower-level half of the claim the test above cannot reach: a write under the clamp
    // must not even make the kqueue itself ready, not merely "ready but harmlessly
    // reinterpreted." Polling the KQUEUE'S OWN fd (a kqueue is itself pollable) with a zero
    // timeout reads the raw pending-event state directly, bypassing `drain_kqueue`/
    // `interpret_read_event` — both of whose non-EOF branches report `MembersRemain` whether
    // the underlying event fired or not, which is exactly why a verdict-only assertion cannot
    // tell "suppressed" from "delivered but harmless" apart. No timing is involved: the write
    // completes (kernel-buffered) before the poll call runs, both on this same thread, in
    // program order — nothing is awaited. A real child (not a bare in-process pipe) holds the
    // write end: `arm` itself refuses a write end this process retains, so proving "arm even
    // succeeds here" needs a holder `write_end_check` reports as `Clear`, not `HeldByUs`.
    let mut cmd = crate::Command::new();
    cmd.executable("/bin/sh")
        .args(["sh", "-c", "echo noise >&3; echo ready >&4; exec cat >/dev/null"]);
    cmd.fd(0, crate::Stdio::pipe_in()).expect("stdin pipe");
    cmd.fd(3, crate::Stdio::pipe_out()).expect("marker pipe");
    cmd.fd(4, crate::Stdio::pipe_out()).expect("report pipe");
    let mut child = cmd.spawn().expect("spawn /bin/sh");
    let marker = child.fd_read_end(3.into()).expect("marker read end");
    let mut report = child.fd_read_end(4.into()).expect("report read end");
    let stdin = child.fd_write_end(crate::Fd::STDIN).expect("stdin write end");

    use std::io::Read;
    let mut byte = [0u8; 1];
    report
        .read_exact(&mut byte)
        .expect("the child wrote to fd 3 before this returns");

    let kq = super::arm(marker.as_fd(), false).expect("arm");
    let mut pfd = libc::pollfd {
        fd: kq.as_fd().as_raw_fd(),
        events: libc::POLLIN,
        revents: 0,
    };
    // SAFETY: `pfd` is a single, correctly-initialized `pollfd`; `poll` writes only within its
    // bounds, and the `1` count matches the slice length passed.
    let rc = unsafe { libc::poll(&mut pfd, 1, 0) };
    assert_eq!(
        rc, 0,
        "NOTE_LOWAT must suppress a wakeup for bytes under the clamp, but the kqueue reports ready"
    );
    drop(stdin);
    child.wait().expect("reap");
}

#[skuld::test]
fn bytes_past_the_low_water_clamp_are_drained_without_a_wrong_verdict() {
    // Exercises `interpret_read_event`'s discard branch for real (below the clamp it is never
    // entered at all — a handful of bytes, as in the test above, cannot reach it). The member
    // writes >64 KiB via `yes | head`, well past the measured clamp, THEN closes fd 3 itself
    // (`exec 3>&-`) so the test's own completion is event-driven, not a fixed wait for
    // "probably done writing by now." A generous bound is still passed to
    // `block_until_drained` as a FAILURE bound (a real regression here should fail fast, not
    // hang the suite), not as the mechanism the assertion depends on.
    let (child, marker, stdin) = spawn_marker_holder("yes | head -c 200000 >&3; exec 3>&-; exec cat >/dev/null");
    assert_eq!(
        block_until_drained(
            marker.as_fd(),
            Some(Instant::now().checked_add(Duration::from_secs(10)))
        )
        .expect("wait past the low-water clamp"),
        TreeDrain::AllMarkersClosed,
        "closing the marker after writing past the clamp must still report drained, not hang or misfire"
    );
    assert_eq!(
        child.is_alive(),
        crate::identity::Liveness::Alive,
        "the member closed only the marker fd, not itself — same false-edge shape as the small case"
    );
    drop(stdin);
    child.wait().expect("reap");
}

#[cfg(feature = "tokio")]
#[skuld::test]
async fn async_wait_resolves_when_the_last_member_exits() {
    // `join!` polling `watch` before `end` is an implementation detail, not a contract — so
    // ordering is enforced with a real, per-call channel, not assumed from poll order.
    // `armed_rx.recv()` (blocking, moved to a blocking-pool thread) only returns once
    // `wait_tree_drained_for_test` has actually armed its kqueue; `drop(stdin)` happens
    // strictly after that.
    let (child, marker, stdin) = spawn_marker_holder("exec cat >/dev/null");
    let fd = marker.as_fd();
    let (armed_tx, armed_rx) = std::sync::mpsc::channel();
    let watch = crate::tokio::wait::wait_tree_drained_for_test(fd, armed_tx);
    let end = async move {
        ::tokio::task::spawn_blocking(move || armed_rx.recv().expect("watch armed"))
            .await
            .unwrap();
        drop(stdin);
    };
    let (watched, ()) = ::tokio::join!(watch, end);
    watched.expect("async drain watch");
    child.wait().expect("reap");
}

#[cfg(feature = "tokio")]
#[skuld::test]
async fn two_concurrent_async_waiters_both_observe_the_drain() {
    // Each waiter owns a private kqueue, so their knotes cannot displace each other.
    // Registering the same raw descriptor twice on the reactor instead would park one waiter
    // forever — but that only manifests across a LIVE-to-DRAINED transition (stickiness means
    // an already-drained descriptor resolves both registrations on the spot even with the
    // collision bug present, silently duplicating the already-drained-resolves-immediately test
    // below instead of catching anything). So both waiters get their own armed handshake, and
    // `drop(stdin)` is provably
    // AFTER both have armed — not left to `tokio::join!`'s poll order, the same reasoning the
    // sibling test above this one already applies.
    let (child, marker, stdin) = spawn_marker_holder("exec cat >/dev/null");
    let fd = marker.as_fd();
    let (a_armed_tx, a_armed_rx) = std::sync::mpsc::channel();
    let (b_armed_tx, b_armed_rx) = std::sync::mpsc::channel();
    let a = crate::tokio::wait::wait_tree_drained_for_test(fd, a_armed_tx);
    let b = crate::tokio::wait::wait_tree_drained_for_test(fd, b_armed_tx);
    let end = async move {
        ::tokio::task::spawn_blocking(move || {
            a_armed_rx.recv().expect("waiter a armed");
            b_armed_rx.recv().expect("waiter b armed");
        })
        .await
        .unwrap();
        drop(stdin);
    };
    let (ra, rb, ()) = ::tokio::join!(a, b, end);
    ra.expect("waiter a");
    rb.expect("waiter b");
    child.wait().expect("reap");
}

#[cfg(feature = "tokio")]
#[skuld::test]
async fn async_wait_resolves_immediately_for_an_already_drained_tree() {
    let (child, marker, stdin) = spawn_marker_holder("exec cat >/dev/null");
    drop(stdin);
    child.wait().expect("reap");
    crate::tokio::wait::wait_tree_drained(marker.as_fd())
        .await
        .expect("already-drained watch");
}

#[cfg(feature = "tokio")]
#[skuld::test]
async fn async_wait_resolves_via_eof_with_small_buffered_bytes() {
    // The async counterpart to the sync small-bytes-are-not-a-drain test above: a few bytes
    // stay below the NOTE_LOWAT clamp, so this resolves via the real EOF from `drop(stdin)`,
    // not via `drain_kqueue`'s discard branch — the test below this one is what exercises that
    // branch, through a write that forces genuine backpressure.
    let mut cmd = crate::Command::new();
    cmd.executable("/bin/sh")
        .args(["sh", "-c", "echo noise >&3; echo ready >&4; exec cat >/dev/null"]);
    cmd.fd(0, crate::Stdio::pipe_in()).expect("stdin pipe");
    cmd.fd(3, crate::Stdio::pipe_out()).expect("marker pipe");
    cmd.fd(4, crate::Stdio::pipe_out()).expect("report pipe");
    let mut child = cmd.spawn().expect("spawn /bin/sh");
    let marker = child.fd_read_end(3.into()).expect("marker read end");
    let report = child.fd_read_end(4.into()).expect("report read end");
    let stdin = child.fd_write_end(crate::Fd::STDIN).expect("stdin write end");

    let fd = marker.as_fd();
    let watch = crate::tokio::wait::wait_tree_drained(fd);
    let end = async move {
        // Blocking read on the report pipe: real synchronization for "the bytes are on the
        // marker now", off the async executor thread so it can't stall the reactor.
        ::tokio::task::spawn_blocking(move || {
            use std::io::Read;
            let mut byte = [0u8; 1];
            let mut report = report;
            report
                .read_exact(&mut byte)
                .expect("child wrote to fd 3 before this returns");
        })
        .await
        .unwrap();
        drop(stdin);
    };
    let (watched, ()) = ::tokio::join!(watch, end);
    watched.expect("async drain watch after discarding bytes");
    child.wait().expect("reap");
}

/// Fills `w` to the kernel's true capacity, synchronously, in this process, and returns the
/// `FIONREAD` count read off `r`, the same pipe's read end (on macOS the write end always reads
/// 0). The first write is 1 MiB so XNU grows the buffer to its maximum inside one syscall;
/// smaller writes let the growth straddle two of them (measured 16384, then 65536). Shared with
/// `deadline`.
fn fill_pipe_to_capacity(r: BorrowedFd<'_>, w: BorrowedFd<'_>) -> i32 {
    let flags = rustix::fs::fcntl_getfl(w).unwrap_or_else(|e| panic!("fcntl F_GETFL failed: {e}"));
    rustix::fs::fcntl_setfl(w, flags | rustix::fs::OFlags::NONBLOCK)
        .unwrap_or_else(|e| panic!("fcntl F_SETFL O_NONBLOCK failed: {e}"));
    let buf = vec![0u8; 1 << 20];
    loop {
        match nix::unistd::write(w, &buf) {
            Ok(_) => continue,
            Err(nix::errno::Errno::EAGAIN) => break,
            Err(nix::errno::Errno::EINTR) => continue,
            Err(e) => panic!("write failed: {e}"),
        }
    }
    fionread(r)
}

/// Whether `kq_fd` — assumed to be a kqueue's own fd, itself pollable — is ALREADY readable,
/// checked with a zero-timeout `kevent` on a brand-new, separate probe kqueue registered for
/// `EVFILT_READ` on it. Non-consuming: this touches only the probe kqueue's own queue, never
/// `kq_fd`'s pending events or registrations.
#[cfg(feature = "tokio")]
fn kqueue_fd_is_already_readable(kq_fd: std::os::fd::RawFd) -> bool {
    use nix::sys::event::{EvFlags, EventFilter, FilterFlag, KEvent, Kqueue};

    let probe_kq = Kqueue::new().expect("probe kqueue");
    let change = KEvent::new(
        kq_fd as usize,
        EventFilter::EVFILT_READ,
        EvFlags::EV_ADD | EvFlags::EV_RECEIPT,
        FilterFlag::empty(),
        0,
        0,
    );
    let add_result = crate::wait::backend::add_with_receipt(&probe_kq, change).expect("register the probe knote");
    assert_eq!(
        add_result, 0,
        "registering EVFILT_READ on the watched kqueue's own fd failed: errno {add_result}"
    );

    let zero = libc::timespec { tv_sec: 0, tv_nsec: 0 };
    let mut events = [KEvent::new(
        0,
        EventFilter::EVFILT_READ,
        EvFlags::empty(),
        FilterFlag::empty(),
        0,
        0,
    )];
    let n = probe_kq
        .kevent(&[], &mut events, Some(zero))
        .expect("zero-timeout poll of the probe kqueue");
    n > 0
}

#[cfg(feature = "tokio")]
#[skuld::test]
async fn async_wait_never_drains_past_the_low_water_clamp() {
    crate::tokio::test_runtime::assert_current_thread();
    // `wait_tree_drained` has no deadline, so past the clamp it must not drain: draining for a
    // stuck writer forever is the unbounded CPU spin this primitive exists to avoid.
    //
    // The seam below is a thread-local, so this needs skuld's default current-thread runtime.

    // This process fills the pipe before `arm`, so nothing can grow it afterwards. The child
    // never writes; it only holds the write end open so the wait has a live holder.
    let (marker_r, marker_w) = std::io::pipe().expect("pipe");
    let queued_before = fill_pipe_to_capacity(marker_r.as_fd(), marker_w.as_fd());
    // The at-clamp precondition is enforced by the readiness probe below.

    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");
    // Moves `marker_w` in: this test's own copy is gone before `arm` runs.
    cmd.fd(
        3,
        crate::Stdio::from_file(std::fs::File::from(std::os::fd::OwnedFd::from(marker_w))),
    )
    .expect("marker pipe");
    let child = cmd.spawn().expect("spawn /bin/sh");
    let fd = marker_r.as_fd();
    assert_eq!(
        child.try_wait().expect("try_wait"),
        None,
        "the holder already exited before this test could observe it"
    );

    // `declined_hook` fires when the watch loop gets a genuine non-EOF event and does not
    // resolve: proof the race below reached and passed judgment on a real event. `select!`
    // polls with the task's real waker, so the reactor registration is the one any caller gets.
    let (declined_tx, mut declined_rx) = ::tokio::sync::mpsc::unbounded_channel();
    let _declined_guard = crate::tokio::wait::declined_hook::DeclinedGuard::install(declined_tx);
    let (armed_tx, armed_rx) = std::sync::mpsc::channel();
    let mut fut = std::pin::pin!(crate::tokio::wait::wait_tree_drained_for_test(fd, armed_tx));

    // One manual poll runs through `arm` (which sends the new kqueue's fd on `armed_tx`) and
    // stops at the reactor await, so `Pending` is the only correct outcome. The no-op waker is
    // fine: the `select!` below drives the future for real.
    match std::future::Future::poll(
        fut.as_mut(),
        &mut std::task::Context::from_waker(std::task::Waker::noop()),
    ) {
        std::task::Poll::Pending => {}
        std::task::Poll::Ready(res) => panic!("wait_tree_drained_for_test resolved on its first poll: {res:?}"),
    }
    let armed_kq_fd = armed_rx.recv().expect("watch armed");

    // The pipe was full before `arm`, so a correctly armed knote is already ready. A zero-timeout
    // `kevent` on a separate probe kqueue checks that without touching `fut`'s queue. This
    // catches an `EV_DISABLE` arm in-process; the nextest override covers what it cannot.
    assert!(
        kqueue_fd_is_already_readable(armed_kq_fd),
        "a knote armed without EV_DISABLE on a full pipe must be immediately readable, but the \
         probe kqueue reported it as not-readable"
    );

    ::tokio::select! {
        biased;
        res = &mut fut => panic!(
            "a pipe proven at its low-water clamp resolved the wait anyway — \
             it must never be drained: {res:?}"
        ),
        _ = declined_rx.recv() => {} // provably saw the real readiness edge and declined to drain on it
    }
    // Distinguishes a mutant that drained some bytes before declining from correct behavior.
    let queued_after = fionread(fd);
    assert_eq!(
        queued_after, queued_before,
        "the marker pipe's buffered byte count changed across the clock-free wait — \
         wait_tree_drained must never drain past the low-water clamp on an unbounded wait"
    );
    assert_eq!(
        child.try_wait().expect("try_wait"),
        None,
        "the holder must still be alive, not exited"
    );

    // A single child, killed through the `Child` handle cosca returned, before that handle
    // reaps it — `docs/principles.md` §10's own exemption.
    child.kill().expect("kill the holder");
    child.wait().expect("reap");
}