cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! Unit tests for the foreign graceful trio's watch-failure ordering (the fault seam is
//! pub(crate), unreachable from tests/). Unix-only: both foreign soft ops are `Unsupported`
//! on Windows before any watch runs. The foreign surface is non-reaping, so the Child twins'
//! reap discriminator (`!id.exists()`) does not exist here; instead the child IGNORES
//! `SIGTERM`, making the escalation's `SIGKILL` the only signal that can terminate it — the
//! owned std handle's reaped status proves the escalation ran despite the watch error.
#![cfg(unix)]

use std::io::Read;
use std::os::unix::process::ExitStatusExt;
use std::time::Duration;

use crate::graceful_hooks::{at, release_at, HookPoint};
use crate::send_log::Capture;
use crate::test_child::foreign::{self, survivor_tree, tree_of};
use crate::test_child::{blocker, StdChild};
use crate::wait::fault;

/// A std child that ignores `SIGTERM` (`trap '' TERM` before `exec`; an ignored disposition
/// survives the exec) and blocks on the piped stdin the returned `std::process::Child` holds. The
/// readiness byte on stdout proves the trap is installed before any signal is sent.
///
/// A test that never sends `SIGKILL` cannot hang on it: `std::process::Child::wait` closes that
/// stdin before waiting, so the stranded `cat` exits 0 at once and fails the `SIGKILL` assertion.
/// Taking the stdin out of the `Child`, or reaping through another handle, would lose that EOF.
fn spawn_term_ignoring_blocker() -> StdChild {
    // Held for the fork itself: a fork landing while a `fdmarker_tests.rs` test's marker write
    // end is transiently open would inherit it into this not-yet-`exec`'d process, and a
    // concurrent sweep could then find and SIGKILL it — see that module's docs.
    let mut child = StdChild::spawn(
        std::process::Command::new("sh")
            .args(["-c", "trap '' TERM; echo r; exec cat"])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped()),
    );
    let mut buf = [0u8; 1];
    child
        .stdout
        .take()
        .expect("piped stdout")
        .read_exact(&mut buf)
        .expect("readiness byte");
    child
}

// A watch failure must not strand the foreign process between the soft signal and the
// escalation: the kill still runs, then the watch error surfaces. A wait that returned the error
// first would leave the SIGTERM-ignoring child alive.
#[skuld::test]
fn foreign_graceful_lone_watch_error_still_escalates() {
    let mut child = spawn_term_ignoring_blocker();
    let p = crate::Process::open_pid(child.id()).expect("open").expect("running");
    fault::set_force_watch_error(true);
    let err = p
        .graceful_shutdown(Duration::from_secs(30))
        .expect_err("the watch error must surface");
    assert!(
        !fault::armed(),
        "seam not consumed — the watch did not run on this thread"
    );
    assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
    // Death proof via the OWNED handle: SIGTERM is ignored, so only the escalation's SIGKILL
    // can have terminated it.
    let status = child.wait().expect("reap");
    assert_eq!(
        status.signal(),
        Some(libc::SIGKILL),
        "child must be force-killed despite the watch error, got {status:?}"
    );
}

// The TREE twin of the same invariant: the hard sweep must still run after a watch failure
// (the old shape propagated it before `kill_tree`, stranding the whole tree). A tree of one
// suffices — the ordering, not the walk's reach, is under test (tests/graceful.rs covers reach).
#[skuld::test]
fn foreign_graceful_tree_watch_error_still_sweeps() {
    let mut child = spawn_term_ignoring_blocker();
    let p = crate::Process::open_pid(child.id()).expect("open").expect("running");
    fault::set_force_watch_error(true);
    let err = p
        .graceful_shutdown_tree(Duration::from_secs(30))
        .expect_err("the watch error must surface");
    assert!(
        !fault::armed(),
        "seam not consumed — the watch did not run on this thread"
    );
    assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
    let status = child.wait().expect("reap");
    assert_eq!(
        status.signal(),
        Some(libc::SIGKILL),
        "root must be swept despite the watch error, got {status:?}"
    );
}

// `terminate_tree` sends `SIGTERM` to the root and to its descendant. The send record is asserted
// before anything waits, so a call that sent nothing fails there, and nothing is released that
// could race the signal.
//
// Mutants: `terminate_tree` sends nothing; sends another signal; stops at the root.
#[skuld::test]
fn foreign_terminate_tree_sigterms_the_root_and_its_descendant() {
    let tree = foreign::blocked_tree();
    let p = crate::Process::open_pid(tree.root.id())
        .expect("open")
        .expect("running");
    let sends = Capture::start();
    p.terminate_tree().expect("terminate_tree");
    foreign::assert_tree_sigtermed(&sends, tree.root.id(), tree.grandchild);
    tree.assert_died_of_sigterm();
}

// The graceful path of the tree shutdown: the walk's `SIGTERM`s are asserted at `AfterTerminate`,
// inside the call, so the root must leave to the soft signal, not to the sweep.
//
// Mutants: `terminate_tree` sends nothing; `graceful_shutdown_tree` skips it.
#[skuld::test]
fn foreign_graceful_shutdown_tree_graceful_path() {
    let tree = foreign::blocked_tree();
    let (root, grandchild) = (tree.root.id(), tree.grandchild);
    let p = crate::Process::open_pid(root).expect("open").expect("running");
    let sends = Capture::start();
    let _armed = at(HookPoint::AfterTerminate, move || {
        foreign::assert_tree_sigtermed(&sends, root, grandchild)
    });
    p.graceful_shutdown_tree(Duration::from_secs(30))
        .expect("graceful_shutdown_tree");
    tree.assert_died_of_sigterm();
}

// The graceful path of the lone shutdown: a blocker dies to `SIGTERM`'s default disposition within
// the grace. Its stdin is released once `terminate` returned (see `release_at`), so a `terminate`
// that sent nothing lets it exit 0 and fails the assertion instead of the grace running out first.
// A sent `SIGTERM` is already pending then, so it beats the release.
//
// Mutants: `os_process::terminate` sends nothing; `graceful_shutdown` skips it.
#[skuld::test]
fn foreign_graceful_shutdown_graceful_path() {
    let mut child = blocker();
    let p = crate::Process::open_pid(child.id()).expect("open").expect("running");
    let stdin = child.stdin.take().expect("piped stdin");
    let _release = release_at(HookPoint::AfterTerminate, stdin);
    p.graceful_shutdown(Duration::from_secs(30)).expect("graceful_shutdown");
    let status = child.wait().expect("reap");
    assert_eq!(status.signal(), Some(libc::SIGTERM), "got {status:?}");
}

// The root ends on the `SIGTERM` and a member that ignores it is left, reparented. The sweep kills the
// members the call's own walk found, by identity, waits for them, and answers `Ok`: the call's listing
// is clear. A root that was waited for as a zombie shows its own status.
//
// Mutant: the sweep walks from the exited root, finds nothing, and answers `Ok` with the member running.
#[skuld::test]
fn foreign_graceful_shutdown_tree_kills_a_member_that_ignores_the_sigterm_after_the_root_exits() {
    let mut tree = survivor_tree();

    tree.process
        .graceful_shutdown_tree(Duration::from_secs(30))
        .expect("every member the walk found is killed");

    for member in &tree.members {
        assert_eq!(
            member.is_alive(),
            crate::identity::Liveness::Dead,
            "{member:?} ignored the SIGTERM and is killed by identity"
        );
    }
    let status = tree.child.wait().expect("reap the root");
    assert_eq!(status.signal(), Some(libc::SIGTERM), "got {status:?}");
}

// Every sweep kills the held members by identity: when the root has exited and the
// sweep's walk cannot be made (the process table cannot be listed), the members the call's own
// `SIGTERM` walk held are killed by identity all the same. The call is an error, and nothing is left
// running.
//
// Mutant: the sweep leaves held members alone when its walk was not made.
#[cfg(target_os = "linux")]
#[skuld::test]
fn foreign_graceful_sweep_whose_walk_is_not_made_kills_the_members_its_sigterm_walk_held() {
    use crate::identity::{FakeKernel, HostKernel};
    let tree = survivor_tree();
    let kernel = std::sync::Arc::new(FakeKernel::over(&HostKernel));
    let settling = tree
        .process
        .begin_graceful(&crate::identity::spawn_kernel(std::sync::Arc::clone(&kernel)))
        .expect("the SIGTERM walk");
    crate::test_child::wait_until_zombie(tree.child.id());
    kernel.state_pids(Err(libc::EIO));

    let err = tree
        .process
        .kill_tree_settling("graceful_shutdown_tree", &settling)
        .expect_err("the walk was not made");

    assert!(matches!(err, crate::error::Error::Unassessable { .. }), "{err:?}");
    for member in &tree.members {
        assert_eq!(
            member.is_alive(),
            crate::identity::Liveness::Dead,
            "{member:?} was held by the SIGTERM walk and is killed by identity"
        );
    }
}

// A sweep whose walk cannot be made over a root that
// outlives the grace kills the member its `SIGTERM` walk held, which the root's child's exit reparented
// out of the root's walk, by identity. The root is left running, and the answer is the walk's own
// `Unassessable`: a retry walks from that root.
//
// Mutant: the sweep keeps the held member when its walk was not made; it kills the root.
#[cfg(target_os = "linux")]
#[skuld::test]
fn foreign_graceful_sweep_whose_walk_is_not_made_over_a_live_root_kills_the_held_member_and_leaves_the_root() {
    use crate::identity::{FakeKernel, HostKernel, Liveness};
    let tree = tree_of(crate::test_child::ROOT_OUTLIVING_THE_GRACE_ARGV);
    let middle = tree
        .process
        .id()
        .children(crate::Recursive::No)
        .expect("the root's children")
        .pop()
        .expect("the root's child");
    let middle = crate::Process::open(middle)
        .expect("open the middle")
        .expect("the middle runs");
    let kernel = std::sync::Arc::new(FakeKernel::over(&HostKernel));
    let settling = tree
        .process
        .begin_graceful(&crate::identity::spawn_kernel(std::sync::Arc::clone(&kernel)))
        .expect("the SIGTERM walk");
    middle.wait().expect("the middle exits on the SIGTERM");
    let running: Vec<_> = tree
        .members
        .iter()
        .copied()
        .filter(|member| member.is_alive() == Liveness::Alive)
        .collect();
    assert_eq!(running.len(), 1, "the member that ignores the SIGTERM runs, reparented");
    kernel.state_pids(Err(libc::EIO));

    let err = tree
        .process
        .kill_tree_settling("graceful_shutdown_tree", &settling)
        .expect_err("the walk was not made");

    assert!(matches!(err, crate::error::Error::Unassessable { .. }), "{err:?}");
    assert_eq!(
        running[0].is_alive(),
        Liveness::Dead,
        "the reparented member was held by the SIGTERM walk and is killed by identity"
    );
    assert_eq!(tree.process.id().is_alive(), Liveness::Alive, "the root is not killed");
    tree.process.kill().expect("end the root");
}

// A root that ignores the `SIGTERM` outlives the grace, and the `SIGTERM` ends its child, which
// reparents the member below it out of the sweep's walk from the root. The member the call's own walk
// reached is killed by identity all the same, as a `Child`'s tree does through its settlement, and the
// call is `Ok`.
//
// The call waits for the child to end before the sweep, so the member is reparented whatever the
// scheduling.
//
// Mutant: the sweep kills only what the walk from the live root finds.
#[skuld::test]
fn foreign_graceful_shutdown_tree_kills_a_member_reparented_while_the_root_outlives_the_grace() {
    let mut tree = tree_of(crate::test_child::ROOT_OUTLIVING_THE_GRACE_ARGV);
    assert_eq!(tree.members.len(), 2, "the child and the member below it");
    let reparented = crate::test_child::wait_for_the_middle_to_exit_after_the_term(tree.process.id());

    tree.process
        .graceful_shutdown_tree(Duration::ZERO)
        .expect("the member its walk reached is killed by identity");

    reparented.assert_fired();

    for member in &tree.members {
        assert_eq!(
            member.is_alive(),
            crate::identity::Liveness::Dead,
            "{member:?} is killed or ended by the SIGTERM"
        );
    }
    let status = tree.child.wait().expect("reap the root");
    assert_eq!(
        status.signal(),
        Some(libc::SIGKILL),
        "the sweep killed the live root: {status:?}"
    );
}

// The `SIGTERM` walk of `begin_graceful` reads the process table through the kernel it is given, and a
// row stated before the call refuses it: the walk is not made, and nothing is signalled.
//
// Mutant: the walk reads through the host's kernel, lists the tree, and signals it.
#[cfg(target_os = "linux")]
#[skuld::test]
fn begin_graceful_walks_through_the_kernel_it_is_given() {
    use crate::identity::{FakeKernel, HostKernel};
    let mut child = blocker();
    let process = crate::Process::open_pid(child.id()).expect("open").expect("running");
    let kernel = std::sync::Arc::new(FakeKernel::over(&HostKernel).on_pids(Err(libc::EIO)));
    let sends = Capture::start();

    let Err(err) = process.begin_graceful(&crate::identity::spawn_kernel(std::sync::Arc::clone(&kernel))) else {
        panic!("the process table cannot be read, so the walk is not made");
    };

    assert!(matches!(err, crate::error::Error::Unassessable { .. }), "{err:?}");
    assert_eq!(sends.entries(), vec![], "nothing was signalled");
    child.kill().expect("end the root");
    child.wait().expect("reap the root");
}

// The settlement of `begin_graceful` holds the kernel the call was given, in its `Walker` as for its
// sweep: three holders of that `Arc` stand while the settlement does, the caller's, the `Walker`'s and the
// sweep's.
//
// Mutant: the `Walker` is built over a kernel of its own.
#[skuld::test]
fn begin_graceful_holds_the_kernel_it_is_given_in_the_settlement_and_its_walker() {
    let mut child = blocker();
    let process = crate::Process::open_pid(child.id()).expect("open").expect("running");
    let kernel = crate::identity::spawn_kernel(crate::identity::HostKernel);

    let Ok(settling) = process.begin_graceful(&kernel) else {
        panic!("the SIGTERM walk");
    };

    assert_eq!(std::sync::Arc::strong_count(&kernel), 3);
    drop(settling);
    assert_eq!(
        std::sync::Arc::strong_count(&kernel),
        1,
        "the settlement held every other"
    );
    child.wait().expect("reap the root");
}

// A walk from an exited root finds nothing, so `kill_tree` says it could not see the tree.
//
// Mutant: the empty walk is `Ok`.
#[skuld::test]
fn foreign_kill_tree_over_an_exited_unreaped_root_is_unassessable() {
    let mut tree = survivor_tree();
    tree.child.kill().expect("kill the root alone");
    crate::test_child::wait_until_zombie(tree.child.id());

    let err = tree
        .process
        .kill_tree()
        .expect_err("a walk from an exited root finds no member");

    assert!(matches!(err, crate::error::Error::Unassessable { .. }), "{err:?}");
}

// `terminate_tree` over an exited root whose walk finds no member is `Unassessable` and sends nothing.
//
// Mutant: the empty walk is `Ok`.
#[skuld::test]
fn foreign_terminate_tree_over_an_exited_root_with_an_empty_walk_is_unassessable_and_sends_nothing() {
    let mut child = blocker();
    let p = crate::Process::open_pid(child.id()).expect("open").expect("running");
    child.kill().expect("kill the root");
    crate::test_child::wait_until_zombie(child.id());
    let sends = Capture::start();

    let err = p
        .terminate_tree()
        .expect_err("a walk from an exited root finds no member");

    assert!(matches!(err, crate::error::Error::Unassessable { .. }), "{err:?}");
    assert_eq!(sends.entries(), vec![], "nothing was sent");
}