use std::time::Duration;
#[cfg(unix)]
use super::armed_deadline_seam::Armed;
use super::{grace_wait, wait_exit};
use crate::identity::ProcessId;
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 grace_wait_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 = grace_wait(id, Duration::from_secs(30)).await.expect("grace_wait");
assert!(exited, "an exited (unreaped) child must report exited");
child.wait().expect("reap");
}
#[skuld::test]
async fn grace_wait_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 = grace_wait(id, Duration::ZERO).await.expect("grace_wait");
assert!(!exited, "a live child at ZERO grace must report still-alive");
child.kill().expect("cleanup");
child.wait().expect("reap");
}
#[skuld::test]
async fn grace_wait_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 = grace_wait(id, Duration::from_secs(30)).await.expect("grace_wait");
assert!(exited, "a stale identity (reaped child) must report exited, never hang");
}
#[skuld::test]
async fn grace_wait_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(grace_wait(id, Duration::from_secs(30)));
child.kill().expect("kill mid-wait");
let exited = watch.await.expect("join").expect("grace_wait");
assert!(exited, "the watch must resolve on the child's exit");
child.wait().expect("reap");
}
#[cfg(windows)]
#[skuld::test]
fn cancel_event_releases_the_blocking_wait() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
let cancel = crate::wait::backend::new_cancel_event().expect("event");
crate::wait::backend::signal_cancel(&cancel);
let exited = crate::wait::backend::block_until_exit_or_cancel(id, None, &cancel).expect("cancellable wait");
assert!(!exited, "a live child with a signaled cancel must report still-alive");
child.kill().expect("cleanup");
child.wait().expect("reap");
}
#[cfg(windows)]
#[skuld::test]
fn cancel_event_signaled_mid_wait_releases_the_blocking_wait() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
let cancel = std::sync::Arc::new(crate::wait::backend::new_cancel_event().expect("event"));
let watcher = std::thread::spawn({
let cancel = cancel.clone();
move || crate::wait::backend::block_until_exit_or_cancel(id, None, &cancel)
});
crate::wait::backend::signal_cancel(&cancel);
let exited = watcher.join().expect("watcher thread").expect("cancellable wait");
assert!(!exited, "a live child with a signaled cancel must report still-alive");
child.kill().expect("cleanup");
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_grace_wait(
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!(grace_wait(id, 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 {
grace_wait(id, grace).await
};
log.extend(rx.try_iter());
Observed {
real_start,
exited: exited.expect("grace_wait"),
log,
}
}
#[cfg(windows)]
#[track_caller]
fn assert_reads_of(
log: &[crate::wait::read_probe::Event],
deadline: Option<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 grace_wait_windows_arms_from_a_past_deadline_fixed_before_spawn_blocking() {
let mut child = std_blocker();
let seen = observed_grace_wait(&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(Some(seen.real_start)));
assert!(reads.iter().all(|r| *r == Some(Duration::ZERO)), "{reads:?}");
}
#[cfg(windows)]
#[skuld::test]
async fn grace_wait_windows_arms_from_a_future_deadline_fixed_before_spawn_blocking() {
let grace = Duration::from_secs(3600);
let mut child = std_blocker();
let seen = observed_grace_wait(&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(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 grace_wait_windows_treats_an_overflowing_grace_as_unbounded() {
let mut child = std_blocker();
let seen = observed_grace_wait(&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 grace_wait_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_grace_wait(&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::wait::backend::arm_proc_exit(target_id)
.expect("arm target")
.expect("a live target arms");
assert!(
crate::wait::backend::arm_note_exit_on(&kq, decoy.id())
.expect("arm decoy")
.is_some(),
"a live decoy arms"
);
decoy.kill().expect("kill decoy");
let afd = ::tokio::io::unix::AsyncFd::with_interest(super::KqueueFd(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 = crate::wait::backend::drain_proc_exit(kq)?;
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 wait_exit_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");
wait_exit(id).await.expect("wait_exit");
child.wait().expect("reap");
}
#[cfg(target_os = "linux")]
#[skuld::test]
async fn wait_exit_names_process_wait_when_pidfd_open_is_refused() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
child.kill().expect("kill");
let forced = crate::wait::backend::fault::force_pidfd_open_errno_once(rustix::io::Errno::ACCESS);
let result = wait_exit(id).await;
drop(forced);
child.wait().expect("reap");
match result {
Err(e @ crate::error::Error::Unsupported { .. }) => assert_eq!(
e.to_string(),
"process wait is not supported on linux: cosca requires pidfd_open (Linux \u{2265} 5.3), \
refused here: pidfd_open answered EACCES"
),
other => panic!("a refused pidfd_open must be Unsupported, got {other:?}"),
}
}
#[skuld::test]
async fn wait_exit_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(wait_exit(id));
child.kill().expect("kill mid-wait");
watch.await.expect("join").expect("wait_exit");
child.wait().expect("reap");
}
#[skuld::test]
async fn grace_wait_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");
wait_exit(id).await.expect("exit observed");
assert!(
grace_wait(id, Duration::ZERO).await.expect("zero probe"),
"an observed-exited child must report exited at ZERO grace"
);
child.wait().expect("reap");
}
#[skuld::test]
async fn wait_exit_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!(wait_exit(id));
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 wait_exit_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!(wait_exit(id));
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)]
#[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");
first.kill().expect("kill");
let guard = super::fault_observer::install(tx);
wait_exit(first_id).await.expect("first watch");
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");
second.kill().expect("kill");
wait_exit(second_id).await.expect("second watch");
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 grace_wait_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 = ProcessId::from_parts_for_test(real.pid(), real.start_token_raw() ^ 1);
let (armed_tx, armed_rx) = std::sync::mpsc::channel();
let _armed_guard = crate::wait::backend::armed_probe::install(armed_tx);
let exited = grace_wait(stale, 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 the_armed_probe_reaches_the_blocking_watch_of_a_live_target() {
let mut child = std_blocker();
let id = ProcessId::of(child.id()).found().expect("identity of live child");
let (tx, rx) = std::sync::mpsc::channel();
let _guard = crate::wait::backend::armed_probe::install(tx);
let exited = grace_wait(id, Duration::ZERO).await.expect("grace_wait");
assert!(!exited, "a live child must report still-alive");
assert_eq!(rx.try_iter().count(), 1, "the wait armed on an unsignalled target once");
child.kill().expect("cleanup");
child.wait().expect("reap");
}
#[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");
other.kill().expect("kill");
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(wait_exit(other_id)).expect("other thread's watch");
other_rx
});
let other_rx = 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(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(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 grace_wait_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!(grace_wait(id, grace));
assert!(
poll_once(fut.as_mut()).is_pending(),
"a live child with an hour of grace"
);
}
assert_eq!(
rx.try_recv().expect("grace_wait 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_grace_wait(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!(grace_wait(id, grace));
assert!(
poll_once(fut.as_mut()).is_pending(),
"a live child must not resolve grace_wait 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 grace_wait_arms_no_timer_for_an_overflowing_grace() {
assert_eq!(armed_by_one_poll_of_grace_wait(Duration::MAX).await, vec![]);
}
#[cfg(unix)]
#[skuld::test(runtime = crate::tokio::test_runtime::paused)]
async fn grace_wait_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_grace_wait(edge).await, vec![Armed::At(t0 + edge)]);
assert_eq!(
armed_by_one_poll_of_grace_wait(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 grace_wait_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!(grace_wait(id, 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!("grace_wait answered {r:?} before its deadline");
}
let exited = fut.await.expect("grace_wait");
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,
"grace_wait answered before t0 + grace on the virtual clock"
);
assert!(
now <= t0 + grace + crate::wait::TOKIO_TIMER_ROUNDING_MARGIN,
"grace_wait 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 grace_wait_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!(grace_wait(id, 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 grace_wait 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 grace_wait_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::wait::block_until_exit(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 = grace_wait(id, Duration::from_secs(60)).await.expect("grace_wait");
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::Command::new();
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::Command::new();
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(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(Some(tokio + s)), tokio, real),
Some(Some(real + s))
);
assert_eq!(
super::to_real_clock_at(Some(Some(tokio)), tokio, real),
Some(Some(real))
);
assert_eq!(super::to_real_clock_at(Some(Some(real)), tokio, real), Some(Some(real)));
assert_eq!(super::to_real_clock_at(Some(None), tokio, real), Some(None));
assert_eq!(super::to_real_clock_at(None, tokio, real), None);
}
#[cfg(unix)]
#[skuld::test(runtime = crate::tokio::test_runtime::paused)]
async fn grace_wait_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 = grace_wait(id, grace).await.expect("grace_wait");
assert!(!exited, "a live child is still alive at the deadline");
assert!(
::tokio::time::Instant::now() >= t0 + grace,
"grace_wait 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(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::Command::new();
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(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");
}