use std::sync::mpsc;
use std::thread::ThreadId;
use super::test_probe::{arm, DropProbe, ReapOutcome};
#[cfg(unix)]
use crate::identity::{ProcessId, Resolved};
use crate::test_child::spawn_async_blocker;
const CHILD_EXIT_BOUND: std::time::Duration = std::time::Duration::from_secs(60);
struct ProbeEnds {
entered: mpsc::Receiver<ThreadId>,
started: mpsc::Receiver<ThreadId>,
gate: mpsc::Sender<()>,
outcome: mpsc::Receiver<ReapOutcome>,
}
fn probe_pair() -> (DropProbe, ProbeEnds) {
let (entered_tx, entered) = mpsc::channel();
let (started_tx, started) = mpsc::channel();
let (gate, gate_rx) = mpsc::channel();
let (outcome_tx, outcome) = mpsc::channel();
(
DropProbe {
entered: entered_tx,
started: started_tx,
gate: gate_rx,
outcome: outcome_tx,
},
ProbeEnds {
entered,
started,
gate,
outcome,
},
)
}
fn private_pool(bound: usize) -> &'static super::LazyPool {
Box::leak(Box::new(super::LazyPool::new(bound)))
}
fn bare_job(origin: ThreadId, probe: Option<DropProbe>) -> super::ReapJob {
let proc = {
let _guard = crate::child::spawn::spawn_lock();
::tokio::process::Command::new(std::env::current_exe().expect("current_exe"))
.args(["--exact", "__cosca_no_such_test__"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.expect("spawn a child that exits")
};
let pid = proc.id().expect("a freshly spawned child has a pid");
super::ReapJob {
os: super::super::OsResources {
proc: Some(super::super::ProcSource::Tokio(proc)),
..Default::default()
},
pid,
origin,
probe,
force_panic: false,
force_release_panic: false,
force_glue_panic: false,
}
}
fn submit_gated(pool: &'static super::LazyPool, count: usize) -> Vec<ProbeEnds> {
let origin = std::thread::current().id();
(0..count)
.map(|_| {
let (probe, ends) = probe_pair();
super::submit_to(pool, bare_job(origin, Some(probe)));
ends
})
.collect()
}
fn release_and_reap(ends: ProbeEnds) {
let ProbeEnds { gate, outcome, .. } = ends;
drop(gate);
assert!(
matches!(outcome.recv(), Ok(ReapOutcome::Reaped(_))),
"a released job must reap"
);
}
fn arm_probe() -> ProbeEnds {
let (probe, ends) = probe_pair();
arm(probe);
ends
}
fn arm_probe_ungated() -> (mpsc::Receiver<ThreadId>, mpsc::Receiver<ReapOutcome>) {
let ends = arm_probe();
drop(ends.gate);
(ends.entered, ends.outcome)
}
#[tokio::test]
async fn drop_signals_the_root_and_returns_before_the_reap() {
use std::io::Read as _;
let ends = arm_probe();
let (child, mut sock) = spawn_async_blocker();
#[cfg(unix)]
let id = child.id();
drop(child);
let dropping = ends.entered.recv().expect("Drop must reach the handoff");
assert_eq!(
dropping,
std::thread::current().id(),
"#[tokio::test] is current-thread"
);
sock.set_read_timeout(Some(CHILD_EXIT_BOUND))
.expect("bound the killed child's exit");
let mut buf = [0u8; 1];
match sock.read(&mut buf) {
Ok(0) => {}
Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {}
other => panic!("root not signalled on the dropping thread before Drop returned: {other:?}"),
}
assert!(
matches!(ends.outcome.try_recv(), Err(mpsc::TryRecvError::Empty)),
"Drop must return before the teardown runs"
);
#[cfg(unix)]
assert_eq!(
ProcessId::of(id.pid()),
Resolved::Found(id),
"the exited child must still be an unreaped zombie while the teardown is gated"
);
drop(ends.gate);
assert!(
matches!(ends.outcome.recv(), Ok(ReapOutcome::Reaped(_))),
"the released teardown must reap"
);
#[cfg(unix)]
assert_ne!(
ProcessId::of(id.pid()),
Resolved::Found(id),
"after the teardown the child's identity must be gone"
);
}
#[tokio::test]
async fn drop_reaps_on_a_worker_thread() {
let (entered, outcome) = arm_probe_ungated();
let (child, _sock) = spawn_async_blocker();
#[cfg(unix)]
let id = child.id();
drop(child);
let dropping = entered.recv().expect("Drop must reach the handoff");
let outcome = outcome.recv().expect("the teardown must report an outcome");
match outcome {
ReapOutcome::Reaped(executing) => assert_ne!(
executing, dropping,
"the reap must run on a worker thread, not the dropping thread"
),
other => panic!("expected Reaped, got {other:?}"),
}
#[cfg(unix)]
assert_ne!(
ProcessId::of(id.pid()),
Resolved::Found(id),
"the teardown must fully reap the child (no lingering process or zombie at its identity)"
);
}
#[tokio::test]
async fn teardown_reports_the_executing_thread_not_the_origin() {
let (probe, ends) = probe_pair();
drop(ends.gate); let origin = std::thread::current().id();
let job = bare_job(origin, Some(probe));
let h = std::thread::spawn(move || super::run_teardown(job));
let executing = h.thread().id();
h.join().expect("the teardown thread must not panic");
assert_ne!(executing, origin, "the teardown must run off the origin thread");
assert_eq!(
ends.outcome.recv().expect("the teardown must report an outcome"),
ReapOutcome::Reaped(executing),
"the reported thread must be the EXECUTING one, not the job's origin"
);
}
#[tokio::test]
async fn each_wedged_job_occupies_its_own_worker_and_the_extra_job_queues() {
let bound = super::REAPER_POOL_THREADS;
let pool = private_pool(bound);
let mut ends = submit_gated(pool, bound + 1);
let extra = ends.pop().expect("bound + 1 jobs were submitted");
let workers: Vec<ThreadId> = ends
.iter()
.map(|e| {
e.started
.recv()
.expect("each of the first `bound` jobs must be taken by a worker of its own")
})
.collect();
assert!(
matches!(extra.started.try_recv(), Err(mpsc::TryRecvError::Empty)),
"with every worker wedged, the extra job must queue rather than run"
);
let first = ends.remove(0);
drop(first.gate);
assert_eq!(
first.outcome.recv().expect("the released job must report an outcome"),
ReapOutcome::Reaped(workers[0]),
"the released job reaps on the worker that took it"
);
assert_eq!(
extra
.started
.recv()
.expect("the queued job must be taken once a worker frees up"),
workers[0],
"the freed worker is the one that drains the queue"
);
release_and_reap(extra);
for e in ends {
release_and_reap(e);
}
}
#[tokio::test]
async fn pool_width_follows_its_bound() {
const BOUND: usize = 1;
const _: () = assert!(BOUND < super::REAPER_POOL_THREADS);
let pool = private_pool(BOUND);
let mut ends = submit_gated(pool, BOUND + 1);
let extra = ends.pop().expect("BOUND + 1 jobs were submitted");
let workers: Vec<ThreadId> = ends
.iter()
.map(|e| e.started.recv().expect("a pool of BOUND must take BOUND jobs at once"))
.collect();
assert!(
matches!(extra.started.try_recv(), Err(mpsc::TryRecvError::Empty)),
"a pool of BOUND must not take a BOUND + 1'th job"
);
let first = ends.remove(0);
drop(first.gate);
assert!(
matches!(first.outcome.recv(), Ok(ReapOutcome::Reaped(_))),
"the released job must reap"
);
assert_eq!(
extra
.started
.recv()
.expect("the queued job must be taken once a worker frees up"),
workers[0],
"a pool of BOUND has no spare worker to take the queued job"
);
release_and_reap(extra);
for e in ends {
release_and_reap(e);
}
}
fn submit_ungated(pool: &'static super::LazyPool) -> mpsc::Receiver<ReapOutcome> {
let (probe, ends) = probe_pair();
drop(ends.gate);
super::submit_to(pool, bare_job(std::thread::current().id(), Some(probe)));
ends.outcome
}
#[tokio::test]
async fn any_spawn_failure_abandons_the_pool_and_the_next_dispatch_retries() {
let pool = private_pool(super::REAPER_POOL_THREADS);
super::fault::set_force_spawn_failures(1);
let outcome = submit_ungated(pool);
assert_eq!(
outcome.try_recv(),
Ok(ReapOutcome::Released),
"a pool that could not start every worker must abandon and release the job in hand"
);
let outcome = submit_ungated(pool);
assert!(
matches!(outcome.recv(), Ok(ReapOutcome::Reaped(_))),
"the abandoned pool leaves its cell empty, so the next dispatch must retry the init"
);
assert_eq!(
super::fault::take_force_spawn_failures(),
0,
"the seam must have been consumed — a flag nothing read cannot fail this test"
);
}
#[tokio::test]
async fn total_spawn_failure_releases_the_job_in_hand() {
let pool = private_pool(super::REAPER_POOL_THREADS);
super::fault::set_force_spawn_failures(super::REAPER_POOL_THREADS);
let outcome = submit_ungated(pool);
assert_eq!(
outcome.try_recv(),
Ok(ReapOutcome::Released),
"with no worker started at all the job must be released in hand"
);
assert_eq!(
super::fault::take_force_spawn_failures(),
0,
"the seam must have been consumed"
);
}
#[tokio::test]
async fn concurrent_first_submits_share_one_init() {
let pool = private_pool(super::REAPER_POOL_THREADS);
let submitters = super::REAPER_POOL_THREADS + 2;
let origin = std::thread::current().id();
let barrier = std::sync::Arc::new(std::sync::Barrier::new(submitters));
let mut outcomes = Vec::new();
let mut handles = Vec::new();
for _ in 0..submitters {
let (probe, ends) = probe_pair();
drop(ends.gate);
outcomes.push(ends.outcome);
let job = bare_job(origin, Some(probe));
let barrier = std::sync::Arc::clone(&barrier);
handles.push(std::thread::spawn(move || {
barrier.wait();
super::submit_to(pool, job);
}));
}
for h in handles {
h.join().expect("a submitting thread must not panic");
}
for outcome in outcomes {
assert!(
matches!(outcome.recv(), Ok(ReapOutcome::Reaped(_))),
"a submitter that spuriously saw no pool would have released its job instead"
);
}
assert_eq!(
pool.inits.load(std::sync::atomic::Ordering::Relaxed),
1,
"the in-lock re-check must admit exactly one init"
);
}
#[tokio::test]
async fn teardown_panic_is_caught_and_reported() {
let (entered, outcome) = arm_probe_ungated();
let (child, _sock) = spawn_async_blocker();
super::fault::set_force_teardown_panic(true);
drop(child);
entered.recv().expect("Drop must reach the handoff");
assert_eq!(
outcome
.recv()
.expect("without the wait region's catch the worker unwinds and no outcome arrives"),
ReapOutcome::Panicked,
"a panicking teardown must be caught and reported"
);
assert!(
!super::fault::take_force_teardown_panic(),
"the fault must have been consumed at submit time"
);
}
#[tokio::test]
async fn release_region_panic_does_not_unwind_run_teardown() {
let (probe, ends) = probe_pair();
drop(ends.gate); let mut job = bare_job(std::thread::current().id(), Some(probe));
job.force_release_panic = true;
let h = std::thread::spawn(move || super::run_teardown(job));
assert!(
h.join().is_ok(),
"run_teardown must not unwind out of its release region"
);
assert!(
ends.outcome.recv().is_err(),
"the panicking release region must drop the probe unsent"
);
}
#[tokio::test]
async fn unkillable_root_is_not_submitted() {
use std::io::{Read as _, Write as _};
let (entered, outcome) = arm_probe_ungated();
let (child, mut sock) = spawn_async_blocker();
let id = child.id();
super::fault::set_force_kill_failure(true);
drop(child);
entered.recv().expect("Drop must reach the handoff");
assert_eq!(
id.is_alive(),
crate::identity::Liveness::Alive,
"an unkillable root must be left running"
);
assert!(
!super::fault::take_force_kill_failure(),
"the fault must have been consumed"
);
sock.write_all(b"x").expect("release the unsignalled child");
sock.set_read_timeout(Some(CHILD_EXIT_BOUND))
.expect("bound the released child's exit");
let mut buf = [0u8; 1];
match sock.read(&mut buf) {
Ok(0) => {}
Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {}
other => panic!("the released child did not exit: {other:?}"),
}
assert!(
outcome.recv().is_err(),
"a child whose kill failed must not be submitted"
);
}
#[tokio::test]
async fn a_worker_survives_a_teardown_that_unwinds() {
let origin = std::thread::current().id();
let (tx, rx) = crossbeam_channel::unbounded::<super::ReapJob>();
let worker = std::thread::spawn(move || super::work(rx));
let (probe, ends) = probe_pair();
drop(ends.gate);
let mut job = bare_job(origin, Some(probe));
job.force_glue_panic = true;
tx.send(job).expect("the worker's receiver is live");
assert!(
ends.outcome.recv().is_err(),
"a teardown that unwinds past the release region reports no outcome"
);
let (probe, ends) = probe_pair();
drop(ends.gate);
tx.send(bare_job(origin, Some(probe)))
.expect("the worker's receiver must have outlived the unwinding teardown");
drop(tx);
worker
.join()
.expect("the recovery guard must not unwind out of `work` and kill the worker");
assert!(
matches!(ends.outcome.recv(), Ok(ReapOutcome::Reaped(_))),
"the surviving worker must keep draining the queue"
);
}