use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use crate::test_child::Console;
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()
}
fn marker_pipe() -> (OwnedFd, OwnedFd) {
let (r, w) = std::io::pipe().expect("pipe");
(OwnedFd::from(r), OwnedFd::from(w))
}
fn never_allocated_fd() -> BorrowedFd<'static> {
unsafe { BorrowedFd::borrow_raw(1_000_000) }
}
fn spawn_marker_holder(script: &str) -> (crate::Child, crate::PipeReader, crate::PipeWriter) {
let mut cmd = crate::test_child::command(Console::Hidden);
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)
}
fn kill_release_reap<T>(child: crate::Child, held: T) {
child.kill().expect("kill the holder");
drop(held);
crate::test_child::assert_killed("the holder", child.wait().expect("reap the holder"));
}
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); assert_eq!(probe(r.as_fd()).expect("probe"), TreeDrain::AllMarkersClosed);
}
#[skuld::test]
fn probe_reports_drained_even_with_bytes_still_buffered() {
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() {
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::test_child::command(Console::Hidden);
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 mut child = cmd.spawn().expect("spawn /bin/sh");
let stdin = child.fd_write_end(crate::Fd::STDIN).expect("stdin write end");
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"
);
kill_release_reap(child, stdin);
}
#[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); 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() {
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(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() {
let _serialize = test_spawn_lock();
let (r, w) = marker_pipe();
let already_past = Instant::now();
drop(w); assert_eq!(
block_until_drained(r.as_fd(), 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() {
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() {
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);
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() {
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() {
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() {
let f = std::fs::File::open("/dev/null").expect("open /dev/null");
assert_eq!(super::write_end_check(f.as_fd()), super::WriteEndCheck::Unassessable);
let bounded = block_until_drained(f.as_fd(), 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:?}"
);
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() {
let (child, marker, stdin) = spawn_marker_holder("exec cat >/dev/null");
assert_eq!(
block_until_drained(marker.as_fd(), Some(Instant::now())).expect("probe"),
TreeDrain::MembersRemain,
"a live marker holder must hold the edge shut"
);
drop(stdin); 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() {
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() {
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() {
let mut cmd = crate::test_child::command(Console::Hidden);
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");
let parents =
crate::containment::enumerate::process_parents(&crate::identity::HostKernel).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(Instant::now())).expect("probe"),
TreeDrain::MembersRemain,
"an orphan at ppid=1 must hold the edge shut after the root is gone"
);
drop(stdin); 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() {
let mut cmd = crate::test_child::command(Console::Hidden);
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(Instant::now())).expect("probe"),
TreeDrain::MembersRemain,
"two live holders must hold the edge shut"
);
drop(stdin_a); assert_eq!(
block_until_drained(marker.as_fd(), 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); 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() {
let mut cmd = crate::test_child::command(Console::Hidden);
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(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() {
let mut cmd = crate::test_child::command(Console::Hidden);
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 fds = [rustix::event::PollFd::new(&kq, rustix::event::PollFlags::IN)];
assert!(
!crate::wait::any_ready_now(&mut fds).expect("poll the kqueue"),
"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() {
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(), 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() {
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::containment::drain_edge::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() {
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::containment::drain_edge::wait_tree_drained_for_test(fd, a_armed_tx);
let b = crate::containment::drain_edge::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::containment::drain_edge::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() {
let mut cmd = crate::test_child::command(Console::Hidden);
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::containment::drain_edge::wait_tree_drained(fd);
let end = async move {
::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");
}
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)
}
#[cfg(feature = "tokio")]
fn kqueue_fd_is_already_readable(kq_fd: std::os::fd::RawFd) -> bool {
use crate::os_process::macos::kqueue::{Kqueue, Subscription};
let probe_kq = Kqueue::new().expect("probe kqueue");
probe_kq
.subscribe(Subscription::Readable {
fd: kq_fd,
low_water: 1,
})
.expect("register the probe knote");
!probe_kq
.poll()
.expect("non-blocking poll of the probe kqueue")
.is_empty()
}
#[cfg(feature = "tokio")]
#[skuld::test]
async fn async_wait_never_drains_past_the_low_water_clamp() {
crate::tokio::test_runtime::assert_current_thread();
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());
let mut cmd = crate::test_child::command(Console::Hidden);
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(std::os::fd::OwnedFd::from(marker_w))),
)
.expect("marker pipe");
let mut child = cmd.spawn().expect("spawn /bin/sh");
let stdin = child.fd_write_end(crate::Fd::STDIN).expect("stdin write end");
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"
);
let (declined_tx, mut declined_rx) = ::tokio::sync::mpsc::unbounded_channel();
let _declined_guard = crate::containment::drain_edge::declined_hook::DeclinedGuard::install(declined_tx);
let (armed_tx, armed_rx) = std::sync::mpsc::channel();
let mut fut = std::pin::pin!(crate::containment::drain_edge::wait_tree_drained_for_test(fd, armed_tx));
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");
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() => {} }
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"
);
kill_release_reap(child, stdin);
}