use std::time::Duration;
#[cfg(target_os = "macos")]
use crate::test_child::Console;
#[cfg(unix)]
use super::armed_deadline_seam::Armed;
use crate::identity::ProcessId;
async fn exited_by_id(id: ProcessId, timeout: Option<Duration>) -> Result<bool, crate::error::Error> {
crate::tokio::drive::exited_opening(|| crate::os_process::open(id), timeout).await
}
fn std_blocker() -> std::process::Child {
crate::test_spawn::spawn(&mut crate::test_child::held_std_blocker(std::process::Stdio::null()))
.expect("spawn std blocker")
}
fn std_blocker_with_stdout() -> std::process::Child {
crate::test_spawn::spawn(&mut crate::test_child::held_std_blocker(std::process::Stdio::piped()))
.expect("spawn std blocker")
}
fn assert_child_still_alive(child: &mut std::process::Child) {
#[cfg(unix)]
crate::test_child::assert_echoes(
child.stdin.as_mut().expect("piped stdin"),
child.stdout.as_mut().expect("piped stdout"),
);
#[cfg(windows)]
{
use std::io::{Read as _, Write as _};
child
.stdin
.as_mut()
.expect("piped stdin")
.write_all(b"x\r\n")
.expect("write to the blocker");
child.stdin = None; let mut output = Vec::new();
child
.stdout
.as_mut()
.expect("piped stdout")
.read_to_end(&mut output)
.expect("read stdout to EOF");
let status = child.wait().expect("the blocker must exit after stdin closes");
assert!(
status.success(),
"the blocker must exit 0 (findstr's own 'a match was found' code), got {status:?}"
);
assert!(
output.windows(1).any(|w| w == b"x"),
"the blocker's stdout must contain the echoed match, got {output:?}"
);
}
}
fn kill_and_reap(child: &mut std::process::Child) {
#[cfg(unix)]
{
child.kill().expect("kill");
child.wait().expect("reap");
}
#[cfg(windows)]
{
_ = child.kill();
_ = child.wait();
}
}
#[cfg(unix)]
fn poll_once<F: std::future::Future>(fut: std::pin::Pin<&mut F>) -> std::task::Poll<F::Output> {
fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop()))
}
#[skuld::test]
async fn exited_by_id_true_for_exited_unreaped_child() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
child.kill().expect("kill");
let exited = exited_by_id(id, Some(Duration::from_secs(30)))
.await
.expect("exited_by_id");
assert!(exited, "an exited (unreaped) child must report exited");
child.wait().expect("reap");
}
#[skuld::test]
async fn exited_by_id_false_for_live_child_at_zero_grace() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
let exited = exited_by_id(id, Some(Duration::ZERO)).await.expect("exited_by_id");
assert!(!exited, "a live child at ZERO grace must report still-alive");
child.kill().expect("cleanup");
child.wait().expect("reap");
}
#[skuld::test]
async fn exited_by_id_true_for_stale_identity() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
child.kill().expect("kill");
child.wait().expect("reap"); let exited = exited_by_id(id, Some(Duration::from_secs(30)))
.await
.expect("exited_by_id");
assert!(exited, "a stale identity (reaped child) must report exited, never hang");
}
#[skuld::test]
async fn exited_by_id_true_when_child_dies_mid_wait() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
let watch = ::tokio::spawn(exited_by_id(id, Some(Duration::from_secs(30))));
child.kill().expect("kill mid-wait");
let exited = watch.await.expect("join").expect("exited_by_id");
assert!(exited, "the watch must resolve on the child's exit");
child.wait().expect("reap");
}
#[cfg(windows)]
struct Observed {
real_start: std::time::Instant,
exited: bool,
log: Vec<crate::wait::read_probe::Event>,
}
#[cfg(windows)]
async fn observed_exited_by_id(
child: &mut std::process::Child,
pin: std::time::Instant,
grace: Duration,
release: bool,
) -> Observed {
use crate::wait::read_probe::{install, Event};
use crate::wait::test_clock::FrozenClockGuard;
let id = ProcessId::of(child.id()).found().expect("identity of live child");
let (tx, rx) = std::sync::mpsc::channel();
let _log = install(tx);
let _tokio_now = super::now_override::install(pin);
let (_clock, real_start) = FrozenClockGuard::install_lagging(Duration::from_secs(1));
let mut log = Vec::new();
let exited = if release {
let (exited, ()) = ::tokio::join!(exited_by_id(id, Some(grace)), async {
loop {
let event = rx.recv().expect("the blocking watch logs a read");
log.push(event);
if matches!(event, Event::Read { .. }) {
break;
}
}
drop(child.stdin.take());
});
exited
} else {
exited_by_id(id, Some(grace)).await
};
log.extend(rx.try_iter());
Observed {
real_start,
exited: exited.expect("exited_by_id"),
log,
}
}
#[cfg(windows)]
#[track_caller]
fn assert_reads_of(
log: &[crate::wait::read_probe::Event],
deadline: Option<std::time::Instant>,
) -> Vec<Option<Duration>> {
use crate::wait::read_probe::Event;
let mark = log
.iter()
.position(|e| *e == Event::Mark("identity verified"))
.expect("the blocking thread verified identity");
let mut results = Vec::new();
for (i, event) in log.iter().enumerate() {
if let Event::Read {
deadline: used,
remaining,
} = event
{
assert!(i > mark, "a remaining read preceded identity verification: {log:?}");
assert_eq!(
*used, deadline,
"a read was made against a re-derived deadline: {log:?}"
);
results.push(*remaining);
}
}
assert!(!results.is_empty(), "the blocking thread never read remaining: {log:?}");
results
}
#[cfg(windows)]
#[skuld::test]
async fn exited_by_id_windows_arms_from_a_past_deadline_fixed_before_spawn_blocking() {
let mut child = std_blocker();
let seen = observed_exited_by_id(&mut child, std::time::Instant::now(), Duration::ZERO, false).await;
kill_and_reap(&mut child);
assert!(!seen.exited, "a live child at ZERO grace must report still-alive");
let reads = assert_reads_of(&seen.log, Some(seen.real_start));
assert!(reads.iter().all(|r| *r == Some(Duration::ZERO)), "{reads:?}");
}
#[cfg(windows)]
#[skuld::test]
async fn exited_by_id_windows_arms_from_a_future_deadline_fixed_before_spawn_blocking() {
let grace = Duration::from_secs(3600);
let mut child = std_blocker();
let seen = observed_exited_by_id(&mut child, std::time::Instant::now(), grace, true).await;
child.wait().expect("reap");
assert!(seen.exited, "the child exited after its stdin closed");
let reads = assert_reads_of(&seen.log, Some(seen.real_start + grace));
for r in reads {
let r = r.expect("a bounded deadline has a remaining time");
assert!(r > Duration::ZERO && r <= grace, "{r:?}");
}
}
#[cfg(windows)]
#[skuld::test]
async fn exited_by_id_windows_treats_an_overflowing_grace_as_unbounded() {
let mut child = std_blocker();
let seen = observed_exited_by_id(&mut child, std::time::Instant::now(), Duration::MAX, true).await;
child.wait().expect("reap");
assert!(seen.exited, "an unbounded watch ends only by the exit");
assert!(assert_reads_of(&seen.log, None).iter().all(Option::is_none));
}
#[cfg(windows)]
#[skuld::test]
async fn exited_by_id_windows_treats_a_grace_inside_the_timer_margin_of_the_ceiling_as_unbounded() {
let mut child = std_blocker();
let pin = std::time::Instant::now();
let grace = crate::wait::instant_near_ceiling(pin).saturating_duration_since(pin) - Duration::from_micros(500);
let seen = observed_exited_by_id(&mut child, pin, grace, true).await;
child.wait().expect("reap");
assert!(seen.exited, "an unbounded watch ends only by the exit");
assert!(assert_reads_of(&seen.log, None).iter().all(Option::is_none));
}
#[cfg(target_os = "macos")]
#[skuld::test]
async fn death_watch_loop_survives_a_non_exit_drain_cycle() {
let mut decoy = std_blocker();
let target = std_blocker();
let target_id = ProcessId::of(target.id()).found().expect("identity of live target");
let kq = crate::os_process::macos::kqueue::arm_proc_exit(target_id)
.expect("arm target")
.expect("a live target arms");
let decoy_exit = crate::os_process::macos::kqueue::Subscription::Process {
pid: decoy.id(),
signals: false,
reap: false,
};
kq.subscribe(decoy_exit).expect("a live decoy arms");
decoy.kill().expect("kill decoy");
let afd = ::tokio::io::unix::AsyncFd::with_interest(kq, ::tokio::io::Interest::READABLE).expect("register");
let target_cell = std::cell::RefCell::new(None);
let mut pending = Some(target);
let watch = super::watch_readable(&afd, |kq| {
let drained = (!kq.poll()?.is_empty()).then_some(());
if let Some(mut t) = pending.take() {
t.kill().expect("kill target mid-cycle");
*target_cell.borrow_mut() = Some(t);
return Ok(None);
}
Ok(drained)
});
watch.await.expect("watch");
let mut target = target_cell
.borrow_mut()
.take()
.expect("target stored by the first cycle");
target.wait().expect("reap target");
decoy.wait().expect("reap decoy");
}
#[cfg(target_os = "linux")]
mod classify {
use ::tokio::io::Ready;
use super::super::classify_pidfd_ready;
#[skuld::test]
fn readable_and_read_closed_mean_exited() {
assert!(matches!(classify_pidfd_ready(Ready::READABLE), Some(Ok(()))));
assert!(matches!(classify_pidfd_ready(Ready::READ_CLOSED), Some(Ok(()))));
}
#[skuld::test]
fn error_readiness_is_surfaced_not_swallowed() {
assert!(matches!(
classify_pidfd_ready(Ready::ERROR | Ready::READABLE),
Some(Err(_))
));
assert!(matches!(classify_pidfd_ready(Ready::ERROR), Some(Err(_))));
}
#[skuld::test]
fn unclassified_readiness_retries_never_a_false_verdict() {
assert!(classify_pidfd_ready(Ready::EMPTY).is_none());
}
}
#[skuld::test]
async fn exited_by_id_unbounded_resolves_for_exited_unreaped_child() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
child.kill().expect("kill");
exited_by_id(id, None).await.expect("exited_by_id");
child.wait().expect("reap");
}
#[skuld::test]
async fn exited_by_id_unbounded_resolves_when_child_dies_mid_wait() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
let watch = ::tokio::spawn(exited_by_id(id, None));
child.kill().expect("kill mid-wait");
watch.await.expect("join").expect("exited_by_id");
child.wait().expect("reap");
}
#[skuld::test]
async fn exited_by_id_zero_reports_an_observed_exit() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
child.kill().expect("kill");
exited_by_id(id, None).await.expect("exit observed");
assert!(
exited_by_id(id, Some(Duration::ZERO)).await.expect("zero probe"),
"an observed-exited child must report exited at ZERO grace"
);
child.wait().expect("reap");
}
#[skuld::test]
async fn exited_by_id_unbounded_cancel_leaves_child_untouched() {
use std::future::Future;
let mut child = std_blocker_with_stdout();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
{
let mut fut = std::pin::pin!(exited_by_id(id, None));
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
if let std::task::Poll::Ready(r) = fut.as_mut().poll(&mut cx) {
panic!("unbounded watch resolved at first poll on a live child: {r:?}");
}
} assert_child_still_alive(&mut child); kill_and_reap(&mut child);
}
#[cfg(windows)]
#[skuld::test]
async fn exited_by_id_unbounded_drop_releases_the_windows_watcher() {
crate::tokio::test_runtime::assert_current_thread();
use std::future::Future;
let (tx, rx) = std::sync::mpsc::channel();
let guard = super::fault_observer::install(tx);
let mut child = std_blocker_with_stdout();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
{
let mut fut = std::pin::pin!(exited_by_id(id, None));
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
if let std::task::Poll::Ready(r) = fut.as_mut().poll(&mut cx) {
panic!("unbounded watch resolved at first poll on a live child: {r:?}");
}
drop(guard);
} rx.recv()
.expect("the blocking watcher must return after the drop released it");
assert_child_still_alive(&mut child); kill_and_reap(&mut child);
}
#[cfg(windows)]
#[skuld::test]
fn fault_observer_guard_uninstalls_on_drop() {
let (tx, rx) = std::sync::mpsc::channel();
{
let _guard = super::fault_observer::install(tx);
}
super::fault_observer::notify_released();
assert_eq!(rx.try_iter().count(), 0);
assert!(super::fault_observer::current().is_none());
}
#[cfg(all(windows, debug_assertions))]
#[skuld::test]
#[should_panic(expected = "nested on the same thread")]
fn fault_observer_install_panics_when_nested() {
let (tx, _rx) = std::sync::mpsc::channel();
let _outer = super::fault_observer::install(tx.clone());
let _inner = super::fault_observer::install(tx);
}
#[cfg(windows)]
async fn watch_then_kill(id: ProcessId, child: &mut std::process::Child) {
use std::future::Future as _;
let mut watch = std::pin::pin!(exited_by_id(id, None));
let first = std::future::poll_fn(|cx| std::task::Poll::Ready(watch.as_mut().poll(cx))).await;
assert!(first.is_pending(), "a live child must not resolve at the first look");
child.kill().expect("kill");
assert!(
watch.await.expect("watch"),
"the watch must resolve on the child's exit"
);
}
#[cfg(windows)]
#[skuld::test]
fn the_relayed_observer_does_not_outlive_its_blocking_call() {
let rt = ::tokio::runtime::Builder::new_current_thread()
.enable_all()
.max_blocking_threads(1)
.thread_keep_alive(Duration::from_secs(3600))
.build()
.expect("build a runtime with a one-thread blocking pool");
rt.block_on(async {
let pool_thread = ::tokio::task::spawn_blocking(|| std::thread::current().id())
.await
.expect("probe the pool thread");
let (tx, rx) = std::sync::mpsc::channel();
let mut first = std_blocker();
let first_id = ProcessId::of(first.id()).found().expect("identity of live child");
let guard = super::fault_observer::install(tx);
watch_then_kill(first_id, &mut first).await;
drop(guard);
first.wait().expect("reap");
assert_eq!(rx.try_iter().count(), 1, "the first watch releases exactly once");
let mut second = std_blocker();
let second_id = ProcessId::of(second.id()).found().expect("identity of live child");
watch_then_kill(second_id, &mut second).await;
second.wait().expect("reap");
assert_eq!(
rx.try_iter().count(),
0,
"a watch with no observer must not notify the previous watch's"
);
let (thread, empty) =
::tokio::task::spawn_blocking(|| (std::thread::current().id(), super::fault_observer::current().is_none()))
.await
.expect("probe the pool thread");
assert_eq!(thread, pool_thread, "the pool must have reused its one thread");
assert!(empty, "the pool thread's slot must be empty after the call");
});
}
#[cfg(windows)]
#[skuld::test]
async fn exited_by_id_resolves_immediately_on_an_identity_mismatch() {
let mut child = std_blocker_with_stdout();
let real = ProcessId::of(child.id()).found().expect("identity of live child");
let stale = real.with_other_value();
let (armed_tx, armed_rx) = std::sync::mpsc::channel();
let _armed_guard = crate::os_process::windows::cancel::armed_probe::install(armed_tx);
let exited = exited_by_id(stale, Some(Duration::from_secs(30)))
.await
.expect("an identity mismatch must resolve, not error");
assert!(
exited,
"HandleIdentity::Different must report exited — the original identity is gone"
);
assert!(
armed_rx.try_recv().is_err(),
"the identity-mismatch fast path must never reach the real wait — armed_probe must not fire"
);
assert_child_still_alive(&mut child);
kill_and_reap(&mut child);
}
#[cfg(windows)]
#[skuld::test]
async fn a_watch_on_another_thread_does_not_notify_this_threads_observer() {
crate::tokio::test_runtime::assert_current_thread();
let (own_tx, own_rx) = std::sync::mpsc::channel();
let _guard = super::fault_observer::install(own_tx);
let mut other = std_blocker();
let other_id = ProcessId::of(other.id()).found().expect("identity of live child");
let handle = std::thread::spawn(move || {
let (other_tx, other_rx) = std::sync::mpsc::channel();
let _guard = super::fault_observer::install(other_tx);
let rt = ::tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("build a current-thread runtime for the other thread");
rt.block_on(watch_then_kill(other_id, &mut other));
(other_rx, other)
});
let (other_rx, mut other) = handle.join().expect("other thread panicked");
other.wait().expect("reap");
assert_eq!(
other_rx.try_iter().count(),
1,
"the other thread's own observer receives exactly its own release"
);
assert!(
own_rx.try_recv().is_err(),
"an unrelated watch's release on another thread must never notify this thread's observer"
);
}
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
async fn cgroup_wait_tree_drained_wakes_when_the_leaf_is_removed_without_a_populated_event() {
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
let fake = FakeLeaf::new("cosca-async-removed-while-waited", true);
let removed = fake.leaf.clone();
let (blocking_tx, blocking_rx) = std::sync::mpsc::channel::<()>();
let remover = std::thread::spawn(move || {
let mut removed_once = false;
while blocking_rx.recv().is_ok() {
if !removed_once {
FakeLeaf::remove(&removed);
removed_once = true;
}
}
});
crate::containment::cgroup::fault::set_drain_blocking_notifier(blocking_tx);
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
let drained = super::cgroup_wait_tree_drained(&leaf, None).await;
crate::containment::cgroup::fault::take_drain_blocking_notifier();
remover.join().expect("remover");
assert_eq!(drained.expect("wait"), TreeDrain::AllMembersExited);
}
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
async fn cgroup_wait_tree_drained_does_not_panic_on_a_near_maximum_deadline() {
use crate::containment::cgroup::test_support::FakeLeaf;
let fake = FakeLeaf::new("cosca-async-near-max-deadline", true);
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
let now = std::time::Instant::now();
let duration =
crate::wait::instant_near_ceiling(now).saturating_duration_since(now) - std::time::Duration::from_micros(500);
let deadline = super::deadline_from(duration);
let fut = super::cgroup_wait_tree_drained(&leaf, deadline);
::tokio::pin!(fut);
::tokio::select! {
biased;
_ = &mut fut => {}
_ = std::future::ready(()) => {}
}
}
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
async fn cgroup_wait_tree_drained_through_arm_at_never_answers_early() {
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
use std::time::{Duration, Instant};
let fake = FakeLeaf::new("cosca-async-wait-tree-fakeleaf-bounded", true);
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
const BOUND: Duration = Duration::from_millis(50);
let start = Instant::now();
let result = super::cgroup_wait_tree_drained(&leaf, Some(start + BOUND))
.await
.expect("wait");
let elapsed = start.elapsed();
assert_eq!(
result,
TreeDrain::MembersRemain,
"a populated leaf that never drains must report MembersRemain once its deadline passes"
);
assert!(
elapsed >= BOUND,
"cgroup_wait_tree_drained returned after {elapsed:?}, before its own {BOUND:?} deadline"
);
}
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
async fn cgroup_wait_tree_drained_arms_the_callers_deadline_instant() {
crate::tokio::test_runtime::assert_current_thread();
use crate::containment::cgroup::test_support::FakeLeaf;
let (tx, rx) = std::sync::mpsc::channel();
let _seam = super::armed_deadline_seam::install(tx);
let fake = FakeLeaf::new("cosca-async-arm-at-deadline", true);
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
let at = super::tokio_now() + Duration::from_secs(3600);
{
let mut fut = std::pin::pin!(super::cgroup_wait_tree_drained(&leaf, Some(at)));
assert!(poll_once(fut.as_mut()).is_pending(), "the fake leaf never drains");
}
assert_eq!(rx.try_recv().expect("the wait site must arm via arm_at"), Armed::At(at));
assert!(rx.try_recv().is_err(), "armed exactly once");
}
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
async fn cgroup_wait_tree_drained_parks_unbounded_with_no_timer() {
crate::tokio::test_runtime::assert_current_thread();
use crate::containment::cgroup::test_support::FakeLeaf;
let (tx, rx) = std::sync::mpsc::channel();
let _seam = super::armed_deadline_seam::install(tx);
let fake = FakeLeaf::new("cosca-async-wait-site-unbounded", true);
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
{
let mut fut = std::pin::pin!(super::cgroup_wait_tree_drained(&leaf, None));
assert!(poll_once(fut.as_mut()).is_pending(), "the fake leaf never drains");
}
assert_eq!(rx.try_recv().expect("an unbounded park is reported"), Armed::Unbounded);
assert!(rx.try_recv().is_err(), "reported exactly once");
}
#[cfg(unix)]
#[skuld::test(runtime = crate::tokio::test_runtime::paused)]
async fn exited_by_id_arms_deadline_froms_instant() {
let (tx, rx) = std::sync::mpsc::channel();
let _seam = super::armed_deadline_seam::install(tx);
let t0 = super::tokio_now();
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
let grace = Duration::from_secs(3600);
{
let mut fut = std::pin::pin!(exited_by_id(id, Some(grace)));
assert!(
poll_once(fut.as_mut()).is_pending(),
"a live child with an hour of grace"
);
}
assert_eq!(
rx.try_recv().expect("exited_by_id must arm via arm_at"),
Armed::At(t0 + grace)
);
assert!(rx.try_recv().is_err(), "armed exactly once");
child.kill().expect("cleanup");
child.wait().expect("reap");
}
#[cfg(unix)]
async fn armed_by_one_poll_of_exited_by_id(grace: Duration) -> Vec<Armed> {
let (tx, rx) = std::sync::mpsc::channel();
let _seam = super::armed_deadline_seam::install(tx);
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
{
let mut fut = std::pin::pin!(exited_by_id(id, Some(grace)));
assert!(
poll_once(fut.as_mut()).is_pending(),
"a live child must not resolve exited_by_id on its first poll (grace {grace:?})"
);
}
child.kill().expect("cleanup");
child.wait().expect("reap");
rx.try_iter().collect()
}
#[cfg(unix)]
#[skuld::test(runtime = crate::tokio::test_runtime::paused)]
async fn exited_by_id_arms_no_timer_for_an_overflowing_grace() {
assert_eq!(armed_by_one_poll_of_exited_by_id(Duration::MAX).await, vec![]);
}
#[cfg(unix)]
#[skuld::test(runtime = crate::tokio::test_runtime::paused)]
async fn exited_by_id_at_the_timer_margin_edge_is_armed_and_one_nanosecond_past_it_is_unbounded() {
let t0 = super::tokio_now();
let span = crate::wait::instant_near_ceiling(t0).saturating_duration_since(t0);
let edge = span - crate::wait::TOKIO_TIMER_ROUNDING_MARGIN;
assert_eq!(
armed_by_one_poll_of_exited_by_id(edge).await,
vec![Armed::At(t0 + edge)]
);
assert_eq!(
armed_by_one_poll_of_exited_by_id(edge + Duration::from_nanos(1)).await,
vec![]
);
}
#[cfg(unix)]
#[skuld::test]
async fn tokio_arms_the_extreme_instant_arm_at_accepts_without_panicking() {
let ceiling = crate::wait::instant_near_ceiling(super::tokio_now());
let at = ceiling - crate::wait::TOKIO_TIMER_ROUNDING_MARGIN;
let mut fut = std::pin::pin!(super::arm_at(at, std::future::pending::<()>()));
assert!(poll_once(fut.as_mut()).is_pending());
}
#[cfg(unix)]
#[skuld::test(runtime = crate::tokio::test_runtime::paused)]
async fn exited_by_id_never_answers_before_its_deadline_on_a_paused_clock() {
let (tx, rx) = std::sync::mpsc::channel();
let _seam = super::armed_deadline_seam::install(tx);
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
let grace = Duration::from_secs(600);
let t0 = ::tokio::time::Instant::now();
let mut fut = std::pin::pin!(exited_by_id(id, Some(grace)));
assert!(poll_once(fut.as_mut()).is_pending());
::tokio::time::advance(grace - Duration::from_secs(1)).await;
if let std::task::Poll::Ready(r) = poll_once(fut.as_mut()) {
panic!("exited_by_id answered {r:?} before its deadline");
}
let exited = fut.await.expect("exited_by_id");
assert!(!exited, "a live child is still alive when the deadline passes");
assert_eq!(
rx.try_recv().expect("armed"),
Armed::At((t0 + grace).into_std()),
"armed at t0 + grace"
);
let now = ::tokio::time::Instant::now();
assert!(
now >= t0 + grace,
"exited_by_id answered before t0 + grace on the virtual clock"
);
assert!(
now <= t0 + grace + crate::wait::TOKIO_TIMER_ROUNDING_MARGIN,
"exited_by_id answered later than the timer's own round-up after t0 + grace"
);
child.kill().expect("cleanup");
child.wait().expect("reap");
}
#[cfg(unix)]
#[skuld::test(runtime = crate::tokio::test_runtime::paused)]
async fn exited_by_id_with_an_overflowing_grace_stays_pending_across_a_virtual_year() {
let (tx, rx) = std::sync::mpsc::channel();
let _seam = super::armed_deadline_seam::install(tx);
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
let mut fut = std::pin::pin!(exited_by_id(id, Some(Duration::MAX)));
assert!(poll_once(fut.as_mut()).is_pending());
::tokio::time::advance(Duration::from_secs(86_400 * 365)).await;
if let std::task::Poll::Ready(r) = poll_once(fut.as_mut()) {
panic!("an unbounded exited_by_id answered {r:?}");
}
assert!(rx.try_recv().is_err(), "no timer may be armed for an unbounded grace");
child.kill().expect("cleanup");
child.wait().expect("reap");
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn exited_by_id_reports_an_exit_pending_when_the_timer_wins_the_first_poll() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
child.kill().expect("kill");
assert!(crate::test_child::exited_through_open(id, None).expect("exit wait"));
let past = super::tokio_now()
.checked_sub(Duration::from_secs(3600))
.expect("an hour before now");
let _now = super::now_override::install(past);
let exited = exited_by_id(id, Some(Duration::from_secs(60)))
.await
.expect("exited_by_id");
assert!(exited, "an exit that preceded the call must be reported, not Ok(false)");
child.wait().expect("reap");
}
#[cfg(target_os = "macos")]
#[skuld::test]
async fn wait_tree_deadline_reports_an_eof_pending_when_the_timer_wins_the_first_poll() {
use std::os::fd::AsFd;
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.executable("/bin/sh").args(["sh", "-c", "cat"]);
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 holding the marker");
let marker = child.fd_read_end(3.into()).expect("marker read end");
drop(child.fd_write_end(crate::Fd::STDIN).expect("stdin write end")); child.wait().expect("reap /bin/sh");
let past = super::tokio_now()
.checked_sub(Duration::from_secs(3600))
.expect("an hour before now");
let _now = super::now_override::install(past);
let deadline = super::deadline_from(Duration::from_secs(60));
let drain = super::wait_tree_deadline(marker.as_fd(), deadline)
.await
.expect("wait_tree_deadline");
assert_eq!(drain, crate::containment::TreeDrain::AllMarkersClosed);
}
#[cfg(target_os = "macos")]
#[skuld::test]
async fn wait_tree_deadline_arms_the_callers_deadline_instant() {
crate::tokio::test_runtime::assert_current_thread();
use std::os::fd::AsFd;
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.executable("/bin/sh").args(["sh", "-c", "cat"]);
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 holding the marker");
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");
let (tx, rx) = std::sync::mpsc::channel();
let _seam = super::armed_deadline_seam::install(tx);
let at = super::tokio_now() + Duration::from_secs(3600);
{
let mut fut = std::pin::pin!(super::wait_tree_deadline(marker.as_fd(), Some(at)));
assert!(poll_once(fut.as_mut()).is_pending(), "an hour-out deadline");
}
assert_eq!(rx.try_recv().expect("the wait site must arm via arm_at"), Armed::At(at));
assert!(rx.try_recv().is_err(), "armed exactly once");
drop(stdin); child.wait().expect("reap /bin/sh");
}
#[cfg(all(unix, debug_assertions))]
#[skuld::test]
#[should_panic(expected = "deadline_from's contract should prevent")]
async fn arm_at_debug_asserts_a_deadline_inside_the_timer_margin() {
let violating = crate::wait::instant_near_ceiling(super::tokio_now());
let mut fut = std::pin::pin!(super::arm_at(violating, std::future::pending::<()>()));
_ = poll_once(fut.as_mut());
}
#[cfg(all(unix, not(debug_assertions)))]
#[skuld::test(runtime = crate::tokio::test_runtime::paused)]
async fn arm_at_waits_unbounded_for_a_deadline_inside_the_timer_margin_in_release() {
let (tx, rx) = std::sync::mpsc::channel();
let _seam = super::armed_deadline_seam::install(tx);
let violating = crate::wait::instant_near_ceiling(super::tokio_now());
assert_eq!(super::arm_at(violating, std::future::ready(7)).await, Some(7));
let mut fut = std::pin::pin!(super::arm_at(violating, std::future::pending::<()>()));
assert!(poll_once(fut.as_mut()).is_pending());
::tokio::time::advance(Duration::from_secs(86_400 * 365)).await;
if let std::task::Poll::Ready(r) = poll_once(fut.as_mut()) {
panic!("an unbounded wait answered {r:?}");
}
assert_eq!(rx.try_iter().collect::<Vec<_>>(), vec![Armed::Unbounded; 2]);
}
#[skuld::test]
fn to_real_clock_preserves_the_remaining_time_across_clocks() {
let real = std::time::Instant::now();
let tokio = real + Duration::from_secs(3600); let s = Duration::from_secs(60);
assert_eq!(super::to_real_clock_at(Some(tokio + s), tokio, real), Some(real + s));
assert_eq!(super::to_real_clock_at(Some(tokio), tokio, real), Some(real));
assert_eq!(super::to_real_clock_at(Some(real), tokio, real), Some(real));
assert_eq!(super::to_real_clock_at(None, tokio, real), None);
}
#[cfg(unix)]
#[skuld::test(runtime = crate::tokio::test_runtime::paused)]
async fn exited_by_id_serves_its_full_grace_on_tokios_clock_after_an_advance() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
::tokio::time::advance(Duration::from_secs(3600)).await;
let t0 = ::tokio::time::Instant::now();
let grace = Duration::from_secs(60);
let exited = exited_by_id(id, Some(grace)).await.expect("exited_by_id");
assert!(!exited, "a live child is still alive at the deadline");
assert!(
::tokio::time::Instant::now() >= t0 + grace,
"exited_by_id answered before t0 + grace on tokio's clock"
);
child.kill().expect("cleanup");
child.wait().expect("reap");
}
#[cfg(target_os = "linux")]
#[skuld::test(runtime = crate::tokio::test_runtime::paused, labels = [crate::test_harness::CGROUP])]
async fn cgroup_wait_tree_drained_judges_expiry_on_tokios_clock() {
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
let fake = FakeLeaf::new("cosca-async-expiry-on-tokio-clock", true);
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
::tokio::time::advance(Duration::from_secs(3600)).await;
let expired = super::tokio_now() - Duration::from_secs(1);
let mut fut = std::pin::pin!(super::cgroup_wait_tree_drained(&leaf, Some(expired)));
match poll_once(fut.as_mut()) {
std::task::Poll::Ready(r) => assert_eq!(r.expect("wait"), TreeDrain::MembersRemain),
std::task::Poll::Pending => panic!("a deadline past on tokio's clock must answer at once"),
}
}
#[cfg(target_os = "macos")]
#[skuld::test(runtime = crate::tokio::test_runtime::paused)]
async fn wait_tree_deadline_judges_expiry_on_tokios_clock() {
use std::os::fd::AsFd;
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.executable("/bin/sh").args(["sh", "-c", "cat"]);
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 holding the marker");
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");
let (tx, rx) = std::sync::mpsc::channel();
let _seam = super::armed_deadline_seam::install(tx);
::tokio::time::advance(Duration::from_secs(3600)).await;
let expired = super::tokio_now() - Duration::from_secs(1);
let drain = super::wait_tree_deadline(marker.as_fd(), Some(expired))
.await
.expect("wait_tree_deadline");
assert_eq!(drain, crate::containment::TreeDrain::MembersRemain);
assert!(rx.try_recv().is_err(), "an expired deadline arms nothing");
drop(stdin);
child.wait().expect("reap /bin/sh");
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn pidfd_exited_within_an_overflowing_grace_waits_with_no_timer() {
use std::os::fd::AsFd as _;
crate::tokio::test_runtime::assert_current_thread();
let mut child = std_blocker();
let pid = child.id();
child.kill().expect("kill the child");
crate::test_child::wait_until_zombie(pid);
let pidfd = rustix::process::pidfd_open(
rustix::process::Pid::from_raw(pid as i32).expect("a positive pid"),
rustix::process::PidfdFlags::empty(),
)
.expect("pidfd_open the zombie");
let (tx, rx) = std::sync::mpsc::channel();
let _seam = super::armed_deadline_seam::install(tx);
let exited = super::pidfd_exited_within(pidfd.as_fd(), Duration::MAX).await;
assert!(matches!(exited, Ok(true)), "{exited:?}");
assert!(rx.try_recv().is_err(), "no timer is armed for a grace that overflows");
child.wait().expect("reap the child");
}