cosca 0.7.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! `CgroupLeaf::release_without_waiting`: bounded work only, whatever the leaf's state.
//!
//! Every test runs the release inside a [`bounded::Section`](crate::bounded::Section), so a wait
//! for the drain panics at once in debug builds instead of hanging.

use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf};
use crate::containment::cgroup::CgroupLeaf;

/// A [`FakeLeaf`] whose `rmdir` answers as cgroupfs does, and an entered leaf on it.
fn entered(name: &str, populated: bool) -> (FakeLeaf, CgroupLeaf) {
    crate::log_capture::install();
    let fake = FakeLeaf::new(name, populated);
    let (path, events) = (fake.leaf.clone(), fake.events.clone());
    fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&path, &events));
    let leaf = entered_leaf_at(fake.leaf.clone());
    (fake, leaf)
}

/// Release `leaf` under the no-blocking contract; return the steps it took and the levels of the
/// records naming `name`.
fn release(leaf: CgroupLeaf, name: &str) -> (Vec<String>, Vec<log::Level>) {
    let mark = crate::log_capture::mark();
    fault::record_leaf_steps();
    {
        let _bounded = crate::bounded::Section::enter();
        leaf.release_without_waiting();
    }
    let steps = fault::take_leaf_steps();
    fault::take_rmdir_hook();
    (steps, crate::log_capture::levels_since(mark, name))
}

/// A leaf that never drains, released while armed: the release returns. A release that ran the
/// blocking `Drop` would wait for the drain, which the debug contract turns into a panic.
#[skuld::test]
fn release_without_waiting_never_runs_the_blocking_drop() {
    let name = "cosca-release-never-blocks";
    let (_fake, leaf) = entered(name, true);
    let _ = release(leaf, name);
}

#[skuld::test]
fn an_armed_undrained_leaf_is_killed_left_behind_and_warned_about() {
    let name = "cosca-release-armed-undrained";
    let (fake, leaf) = entered(name, true);
    let mark = crate::log_capture::mark();
    let (steps, levels) = release(leaf, name);

    assert_eq!(steps, ["rmdir populated 1", "kill"]);
    assert_eq!(fake.kill_written(), crate::containment::cgroup::KILL_PAYLOAD);
    assert!(fake.leaf.exists(), "an undrained leaf is left behind");
    assert_eq!(levels, [log::Level::Warn]);
    let records = crate::log_capture::records_since(mark, name);
    assert!(
        records[0].contains("wait_tree"),
        "the warning must point at wait_tree().await, got {records:?}"
    );
}

#[skuld::test]
fn a_drained_leaf_is_removed_without_a_kill_and_without_a_warning() {
    let name = "cosca-release-drained";
    let (fake, leaf) = entered(name, false);
    let (steps, levels) = release(leaf, name);

    assert_eq!(steps, ["rmdir populated 0"]);
    assert!(!fake.leaf.exists(), "a drained leaf is removed");
    assert_eq!(levels, Vec::<log::Level>::new());
}

/// The kill lands before the release reads the drain: the leaf is swept and removed.
#[skuld::test]
fn a_leaf_that_drains_by_the_time_of_the_read_is_swept_and_removed() {
    crate::log_capture::install();
    let name = "cosca-release-drains-after-kill";
    let fake = FakeLeaf::new(name, true);
    let (path, events) = (fake.leaf.clone(), fake.events.clone());
    let first = std::cell::Cell::new(true);
    fault::set_rmdir_hook(move |_| {
        if first.replace(false) {
            // The members exit while the first rmdir is refused.
            FakeLeaf::set_populated(&events, false);
            return Err(std::io::Error::from_raw_os_error(libc::EBUSY));
        }
        FakeLeaf::rmdir(&path, &events)
    });
    let leaf = entered_leaf_at(fake.leaf.clone());
    let (steps, levels) = release(leaf, name);

    assert_eq!(steps, ["rmdir populated 1", "kill", "rmdir populated 0"]);
    assert_eq!(
        fake.kill_written(),
        crate::containment::cgroup::KILL_PAYLOAD,
        "the release must write cgroup.kill, not only record the step"
    );
    assert!(!fake.leaf.exists());
    assert_eq!(levels, Vec::<log::Level>::new());
}

/// Killed by this handle and disarmed after (`Child::detach`): the release does not write the kill
/// again, and warns when the leaf has not drained. The armed twin is
/// `an_armed_leaf_this_handle_killed_is_not_killed_again_and_warned_about`.
///
/// Mutant: the release writes `cgroup.kill` again after a landed write.
#[skuld::test]
fn a_disarmed_leaf_this_handle_killed_is_not_killed_again_and_warned_about() {
    let name = "cosca-release-disarmed-killed";
    let (fake, leaf) = entered(name, true);
    leaf.hard_kill().expect("kill the tree");
    leaf.disarm();
    fake.clear_kill();
    let (steps, levels) = release(leaf, name);

    assert_eq!(steps, ["rmdir populated 1"]);
    assert_eq!(fake.kill_written(), b"", "the landed kill is not written again");
    assert!(fake.leaf.exists());
    assert_eq!(levels, [log::Level::Warn]);
}

/// Armed twin of the previous test: the handle killed the tree (`kill_tree()`) and was dropped armed.
///
/// Mutant: the release writes `cgroup.kill` again after a landed write.
#[skuld::test]
fn an_armed_leaf_this_handle_killed_is_not_killed_again_and_warned_about() {
    let name = "cosca-release-armed-killed";
    let (fake, leaf) = entered(name, true);
    leaf.hard_kill().expect("kill the tree");
    fake.clear_kill();
    let (steps, levels) = release(leaf, name);

    assert_eq!(steps, ["rmdir populated 1"]);
    assert_eq!(fake.kill_written(), b"", "the landed kill is not written again");
    assert!(fake.leaf.exists());
    assert_eq!(levels, [log::Level::Warn]);
}

/// A tree the caller asked to leave running is not killed and not a leak: `debug`.
#[skuld::test]
fn a_disarmed_never_killed_leaf_is_never_killed_and_logs_at_debug() {
    let name = "cosca-release-disarmed-never-killed";
    let (fake, leaf) = entered(name, true);
    leaf.disarm();
    let (steps, levels) = release(leaf, name);

    assert_eq!(steps, ["rmdir populated 1"]);
    assert_eq!(fake.kill_written(), b"", "nothing may write cgroup.kill");
    assert!(fake.leaf.exists());
    assert_eq!(levels, [log::Level::Debug]);
}

/// A kill the caller attempted and that failed is a mechanism failure, not a request to leave
/// the tree running.
#[skuld::test]
fn a_disarmed_leaf_whose_kill_attempt_failed_is_warned_about_and_not_killed_again() {
    let name = "cosca-release-disarmed-kill-failed";
    let (fake, leaf) = entered(name, true);
    std::fs::remove_file(fake.leaf.join("cgroup.kill")).expect("remove cgroup.kill");
    std::fs::create_dir(fake.leaf.join("cgroup.kill")).expect("make cgroup.kill unwritable");
    // A kill the kernel took empties the leaf. This write is refused, so it never does. A call
    // that returns `Ok` anyway (whether or not it reached the write) drains the fake here, so the
    // `expect_err` below fails by assertion and the unwinding drop has nothing to await.
    let killed = leaf.hard_kill();
    if killed.is_ok() {
        FakeLeaf::set_populated(&fake.events, false);
    }
    killed.expect_err("the forced failure");
    leaf.disarm();
    let (steps, levels) = release(leaf, name);

    assert_eq!(steps, ["rmdir populated 1"]);
    assert_eq!(levels, [log::Level::Warn]);
}

/// A tree that exited on its own is swept and removed, though nobody killed it.
#[skuld::test]
fn a_disarmed_leaf_that_drained_on_its_own_is_swept_and_removed() {
    let name = "cosca-release-disarmed-self-drained";
    let fake = FakeLeaf::new(name, false);
    std::fs::create_dir(fake.leaf.join("leftover-child")).expect("leave an empty child cgroup");
    crate::log_capture::install();
    let (path, events) = (fake.leaf.clone(), fake.events.clone());
    fault::set_rmdir_hook(move |p| {
        if p.join("leftover-child").exists() {
            return Err(std::io::Error::from_raw_os_error(libc::EBUSY));
        }
        FakeLeaf::rmdir(&path, &events)
    });
    let leaf = entered_leaf_at(fake.leaf.clone());
    leaf.disarm();
    let (steps, levels) = release(leaf, name);

    assert_eq!(steps, ["rmdir populated 0", "rmdir populated 0"], "no kill");
    assert!(!fake.leaf.exists());
    assert_eq!(levels, Vec::<log::Level>::new());
}

/// An armed leaf whose kill write fails is left behind and warned about, naming the kill.
#[skuld::test]
fn an_armed_leaf_whose_kill_write_fails_is_warned_about() {
    let name = "cosca-release-armed-kill-fails";
    let (fake, leaf) = entered(name, true);
    std::fs::remove_file(fake.leaf.join("cgroup.kill")).expect("remove cgroup.kill");
    std::fs::create_dir(fake.leaf.join("cgroup.kill")).expect("make cgroup.kill unwritable");
    let mark = crate::log_capture::mark();
    let (steps, levels) = release(leaf, name);

    assert_eq!(steps, ["rmdir populated 1"]);
    assert_eq!(levels, [log::Level::Warn]);
    assert!(crate::log_capture::records_since(mark, name)[0].contains("cgroup.kill failed"));
}

/// A `cgroup.kill` that failed is final: the release writes nothing more, leaves the leaf behind and
/// warns once. The fault fails only the first write, so a second would be recorded as a kill.
///
/// Mutant: the release writes `cgroup.kill` again after a failed write.
#[skuld::test]
fn an_armed_leaf_whose_earlier_kill_failed_is_not_killed_again_on_release() {
    let name = "cosca-release-armed-earlier-kill-failed";
    let (fake, leaf) = entered(name, true);
    {
        let _first_write_fails = fault::fail_next_kill_write();
        leaf.hard_kill().expect_err("the forced failure");
    }
    let mark = crate::log_capture::mark();
    let (steps, levels) = release(leaf, name);

    assert_eq!(steps, ["rmdir populated 1"], "no second write");
    assert_eq!(fake.kill_written(), b"", "nothing wrote cgroup.kill");
    assert!(fake.leaf.exists(), "the leaf is left behind");
    assert_eq!(levels, [log::Level::Warn]);
    assert!(crate::log_capture::records_since(mark, name)[0].contains("cgroup.kill failed"));
}

/// A leaf whose `rmdir` is refused as busy and whose `cgroup.events` has no `populated` field, so
/// the release cannot read the drain.
fn entered_unreadable(name: &str) -> (FakeLeaf, CgroupLeaf) {
    crate::log_capture::install();
    let fake = FakeLeaf::new(name, true);
    std::fs::write(&fake.events, "frozen 0\n").expect("rewrite cgroup.events");
    fault::set_rmdir_hook(|_| Err(std::io::Error::from_raw_os_error(libc::EBUSY)));
    let leaf = entered_leaf_at(fake.leaf.clone());
    (fake, leaf)
}

/// What a release of `leaf` logged about a drain it could not read: one record, at `level`, that
/// carries the read's own error and does not call the tree undrained.
fn assert_unreadable_drain_is_reported(leaf: CgroupLeaf, name: &str, level: log::Level) {
    let mark = crate::log_capture::mark();
    let (_, levels) = release(leaf, name);
    assert_eq!(levels, [level]);
    let records = crate::log_capture::records_since(mark, name);
    assert!(
        records[0].contains("its drain could not be read") && records[0].contains("no 'populated' field"),
        "the record must carry the read error, got {records:?}"
    );
    assert!(
        !records[0].contains("has not drained"),
        "a failed read is not a slow drain, got {records:?}"
    );
}

/// Mutant: the `Err` from `drain_now` falls into the same arms as `MembersRemain`.
#[skuld::test]
fn an_armed_leaf_whose_drain_cannot_be_read_reports_the_read_error() {
    let name = "cosca-release-armed-unreadable";
    let (_fake, leaf) = entered_unreadable(name);
    assert_unreadable_drain_is_reported(leaf, name, log::Level::Warn);
}

#[skuld::test]
fn a_disarmed_never_killed_leaf_whose_drain_cannot_be_read_reports_the_read_error_at_debug() {
    let name = "cosca-release-disarmed-unreadable";
    let (_fake, leaf) = entered_unreadable(name);
    leaf.disarm();
    assert_unreadable_drain_is_reported(leaf, name, log::Level::Debug);
}

#[skuld::test]
fn a_disarmed_leaf_whose_kill_failed_and_drain_cannot_be_read_reports_the_read_error() {
    let name = "cosca-release-kill-failed-unreadable";
    let (fake, leaf) = entered_unreadable(name);
    std::fs::remove_file(fake.leaf.join("cgroup.kill")).expect("remove cgroup.kill");
    std::fs::create_dir(fake.leaf.join("cgroup.kill")).expect("make cgroup.kill unwritable");
    leaf.hard_kill().expect_err("the forced failure");
    leaf.disarm();
    assert_unreadable_drain_is_reported(leaf, name, log::Level::Warn);
}

/// The pump a wait started is owned by the leaf, and the release ends it: the pump's own record
/// says it ended by the time the release returns, since the release joins it.
///
/// Mutant: `release_without_waiting` leaves the pump running, or does not join it.
#[skuld::test]
fn release_stops_and_joins_the_leafs_pump() {
    let name = "cosca-release-joins-pump";
    let (_fake, leaf) = entered(name, true);
    // A wait that blocks starts the pump.
    let step = leaf.drain_step(None).expect("step the drain");
    assert!(matches!(step, crate::containment::cgroup::DrainStep::Block { .. }));
    assert_eq!(fault::pumps_of(name), (1, 0), "the wait must start the pump");
    drop(step);

    let _ = release(leaf, name);
    assert_eq!(fault::pumps_of(name), (1, 1), "the release must stop and join the pump");
}