cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! Unit tests for the reactor-native waits in `tokio::wait`, and for the async exit watch
//! (`tokio::drive::exited_opening`) on real processes opened by number. In the library because they are
//! `pub(crate)`. Death-proof discipline: a generous grace on an already-dead child is a
//! failure bound (the exit event precedes the call); `Duration::ZERO` on a live child makes
//! the timeout branch deterministic.

use std::time::Duration;

#[cfg(target_os = "macos")]
use crate::test_child::Console;
use crate::test_child::{blocker, blocker_with};

// This module is declared INSIDE src/tokio/wait.rs, so `super` is `tokio::wait` itself.
#[cfg(unix)]
use super::armed_deadline_seam::Armed;
use crate::identity::ProcessId;

/// The exit watch these tests drive: [`exited_held`](crate::tokio::drive::exited_held) over the
/// process `id` names; one that is gone has exited. Nothing outside the tests watches by number.
async fn exited_by_id(id: ProcessId, timeout: Option<Duration>) -> Result<bool, crate::error::Error> {
    let Some(process) = crate::os_process::open(id)? else {
        return Ok(true);
    };
    crate::tokio::drive::exited_held(&*process, timeout).await
}

/// Proves `child` (a [`blocker_with`] whose stdout is piped) is genuinely still alive: `is_alive()` alone
/// races the asynchronous `SIGKILL`/`TerminateProcess`. On Unix, round-trips a byte through the
/// piped stdout. On Windows, closes stdin and requires a clean exit and
/// the echoed line, as `child::graceful_tests::assert_still_running` does, which reaps `child`.
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; // close stdin: EOF, the blocker can now finish and exit
        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 on EOF, got {status:?}");
        assert!(
            output.windows(1).any(|w| w == b"x"),
            "the blocker's stdout must contain the echoed line, got {output:?}"
        );
    }
}

/// Polls `fut` once: all code up to the first suspension (including the seam) runs inside that poll.
#[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 = blocker();
    let id = ProcessId::of(child.id()).found().expect("identity of live child");
    child.kill().expect("kill");
    // NOT reaped yet (no wait): on Unix the child is a zombie — the watch must still see the
    // exit.
    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");
}

#[skuld::test]
async fn exited_by_id_false_for_live_child_at_zero_grace() {
    let child = 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");
}

#[skuld::test]
async fn exited_by_id_true_for_stale_identity() {
    let mut child = blocker();
    let id = ProcessId::of(child.id()).found().expect("identity of live child");
    child.kill().expect("kill");
    child.wait().expect("reap"); // fully gone; the pid may even be recycled
    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() {
    // The live-then-exits path: the watch arms on a LIVE child and must resolve on the real
    // exit event (our own kill). Whether the kill lands before or after arming, the result
    // must be `true`.
    let mut child = 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");
}

// Drive the REAL macOS watch loop through its clear_ready + re-await cycle with genuine
// kernel events: a DECOY second NOTE_EXIT filter on the same kqueue supplies the first wake;
// the scripted drain consumes it (keeping the kqueue level low, so clear_ready cannot miss a
// wake) but reports "no exit" — the loop must re-await, and the target's real exit must still
// resolve it. Every wake is a real kernel event.
#[cfg(target_os = "macos")]
#[skuld::test]
async fn death_watch_loop_survives_a_non_exit_drain_cycle() {
    let mut decoy = blocker();
    let target = 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");
    // Arm the decoy on the SAME kqueue.
    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"); // the first, non-target wake

    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() {
            // First cycle (the decoy's event, consumed above): report "no exit" so the loop
            // clear_readys and re-awaits; only NOW create the target's exit event.
            t.kill().expect("kill target mid-cycle");
            *target_cell.borrow_mut() = Some(t);
            return Ok(None);
        }
        Ok(drained)
    });
    watch.await.expect("watch");
    let _target = target_cell
        .borrow_mut()
        .take()
        .expect("target stored by the first cycle");
}

// The POLLERR branch and the readiness contract, via synthetic `Ready` values: they pin the branch
// logic only. The live-path tests above run the real pidfd -> epoll -> mio -> `AsyncFd` mapping.
#[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() {
        // tokio's documented false-positive wake: not an exit (would skip escalation on a
        // live child), not an error (would force-kill a graceful exit) — re-await.
        assert!(classify_pidfd_ready(Ready::EMPTY).is_none());
    }
}

#[skuld::test]
async fn exited_by_id_unbounded_resolves_for_exited_unreaped_child() {
    let mut child = blocker();
    let id = ProcessId::of(child.id()).found().expect("identity of live child");
    child.kill().expect("kill");
    // NOT reaped: the exit event precedes the call, so the unbounded watch must resolve.
    exited_by_id(id, None).await.expect("exited_by_id");
}

#[skuld::test]
async fn exited_by_id_unbounded_resolves_when_child_dies_mid_wait() {
    // Arm on a LIVE child; our own kill is the real exit event. Race-tolerant either side.
    let mut child = 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");
}

#[skuld::test]
async fn exited_by_id_zero_reports_an_observed_exit() {
    // The ZERO one-shot probe must see an already-exited (zombie) child — the sync/async
    // parity case a plain timeout(ZERO, ..) gets wrong (the AsyncFd readiness of a zombie
    // needs a reactor round-trip the zero timer would win against).
    let mut child = blocker();
    let id = ProcessId::of(child.id()).found().expect("identity of live child");
    child.kill().expect("kill");
    // Observe the exit as a real event WITHOUT reaping: wait for it via the unbounded watch
    // (30 s-class bound is the harness), then probe at ZERO.
    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"
    );
}

#[skuld::test]
async fn exited_by_id_unbounded_cancel_leaves_child_untouched() {
    use std::future::Future;
    // Poll the unbounded watch exactly once (arms it), then drop — the watch is signal-free,
    // so the child must still be alive; it dies only by the test's own kill.
    let mut child = blocker_with(|cmd| {
        cmd.stdout(std::process::Stdio::piped());
    });
    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); // a cancelled watch must not affect the child
}

// A live child watched under an identity naming its pid but a wrong start token is `Opened::Found`
// + `HandleIdentity::Different` on every run, with no dependence on pid-recycling timing. The
// watch resolves as exited at its first poll, without waiting.
#[cfg(windows)]
#[skuld::test]
async fn exited_by_id_resolves_immediately_on_an_identity_mismatch() {
    let mut child = blocker_with(|cmd| {
        cmd.stdout(std::process::Stdio::piped());
    });
    let real = ProcessId::of(child.id()).found().expect("identity of live child");
    let stale = real.with_other_value();

    let mut watch = std::pin::pin!(exited_by_id(stale, Some(Duration::from_secs(30))));
    let std::task::Poll::Ready(answer) = std::future::Future::poll(
        watch.as_mut(),
        &mut std::task::Context::from_waker(std::task::Waker::noop()),
    ) else {
        panic!("an identity mismatch waits for nothing");
    };
    assert!(
        answer.expect("an identity mismatch must resolve, not error"),
        "HandleIdentity::Different must report exited — the original identity is gone"
    );

    // The watch resolved on the STALE identity, so it must not have touched this live child.
    assert_child_still_alive(&mut child);
}

/// The async cgroup drain wait wakes when the leaf is removed, even with no event on
/// `cgroup.events` — the removal can cancel the one notification a drain sends. A pump that never
/// broadcasts hangs this test; `a_changed_batch_notifies_a_listener_that_was_there_before_it` fails
/// it by assertion.
#[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();
    // One-shot: `drain_step` can legally re-block (a spurious wake, or the removal notification
    // racing a stale re-read), and the leaf is gone by then.
    let _remover = crate::wait::block_probe::on_drain_block(move || FakeLeaf::remove(&removed));
    let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
    let drained = crate::containment::drain_edge::cgroup_wait_tree_drained(&leaf, None).await;

    assert_eq!(drained.expect("wait"), TreeDrain::AllMembersExited);
}

/// A deadline within tokio's own ~1ms round-up margin of `Instant`'s ceiling must not panic:
/// `crate::wait::deadline_from` saturates it to unbounded before `drain_step` ever sees it, so
/// this call takes the `listener.await` arm, never the bounded one.
#[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();
    // 500µs short of the true ceiling: comfortably more than the time this takes to reach
    // `deadline_from`'s own `Instant::now()` call, landing within the 1ms margin this exercises.
    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 = crate::containment::drain_edge::cgroup_wait_tree_drained(&leaf, deadline);
    ::tokio::pin!(fut);
    // A single poll is enough: reaching here without panicking is the proof. The fake leaf never
    // drains, so a correct call is Pending either way — nothing here needs it to resolve.
    ::tokio::select! {
        biased;
        _ = &mut fut => {}
        _ = std::future::ready(()) => {}
    }
}

/// `cgroup_wait_tree_drained`'s bounded arm, driven end to end on a `FakeLeaf` (no cgroup
/// needed): a populated leaf that never drains must answer `MembersRemain` no earlier than the
/// caller's own deadline. No upper bound is asserted — only that it never answers early.
#[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 = crate::containment::drain_edge::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"
    );
}

/// The Linux wait site is armed, through `arm_at`, with the caller's deadline instant exactly.
/// Populated `FakeLeaf` (no real cgroup), so `drain_step` reaches its `Block` arm.
#[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!(crate::containment::drain_edge::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");
}

/// The async wait site's unbounded arm reports an unbounded park, and arms no timer.
#[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!(crate::containment::drain_edge::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");
}

// Bounded waits arm the caller's deadline via `arm_at`, never earlier or later -----

/// exited_by_id (site 1) arms `deadline_from`'s instant: `t0 + grace` on the paused clock.
#[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 child = 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");
}

/// Polls `exited_by_id(id, Some(grace))` once on a live child and returns what the seam saw.
#[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 child = 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:?})"
        );
    }
    rx.try_iter().collect()
}

/// An overflowing grace is UNBOUNDED, not a far-future deadline: no timer is armed at all (a
/// fallback deadline, at any distance, would report to the seam), and no early `Ok(false)`.
#[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![]);
}

/// The 1 ms margin's edge at site 1, on the paused clock: a grace landing exactly `MARGIN` short
/// of `Instant`'s ceiling is armed as is, and one nanosecond further is unbounded.
#[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![]
    );
}

/// tokio's own boundary, on real tokio: the extreme instant `arm_at` accepts, `ceiling - MARGIN`,
/// arms without a panic, so a larger tokio round-up breaks this test rather than the margin.
#[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());
}

/// "Never early" on tokio's virtual clock (`start_paused`): with the child alive throughout, the
/// only way `exited_by_id` resolves is its timer, and virtual time is auto-advanced to exactly the
/// armed deadline. It must answer `Ok(false)` only once the clock has reached `t0 + grace`.
#[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 child = 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)));
    // The first poll arms the deadline at t0 + grace; the advance then stops one second short.
    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"
    );
}

/// An unbounded grace on the paused clock: virtual time can pass a year and `exited_by_id` is still
/// pending, and nothing was armed (no fallback deadline of any length).
#[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 child = 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");
}

// A timer that wins the first poll still answers from a final probe -----
// `Timeout` polls the inner future first, but a fresh reactor registration reports nothing until a
// driver turn; a deadline already past then fires the timer with the event still unreported. The
// `now_override` makes the deadline past on that first poll, with no timing involved.

/// Site 1: the child exited (unreaped) before the call. Linux only: the pidfd of a zombie
/// registers with the reactor, which reports nothing until a driver turn, whereas macOS detects an
/// already-exited process while arming and never reaches the timer.
#[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 = blocker();
    let id = ProcessId::of(child.id()).found().expect("identity of live child");
    child.kill().expect("kill");
    // `kill` only signals: block (non-reaping) until the exit has really happened.
    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)");
}

/// Site 2: every holder of the marker's write end exited before the call.
#[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")); // `cat` sees EOF
    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 = crate::containment::drain_edge::wait_tree_deadline(marker.as_fd(), deadline)
        .await
        .expect("wait_tree_deadline");
    assert_eq!(drain, crate::containment::TreeDrain::AllMarkersClosed);
}

/// `wait_tree_deadline` (site 2) arms the caller's own instant. The marker's write end must be
/// held by something other than this process (`arm`'s `refuse_if_write_end_held` refuses
/// otherwise), so a real `/bin/sh` holds it on fd 3 until this test closes its stdin. No
/// `test_spawn_lock()`: `Command::spawn` takes it itself.
#[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!(crate::containment::drain_edge::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); // `cat` sees EOF and exits
    child.wait().expect("reap /bin/sh");
}

// `arm_at` owns the timer-margin contract, on every unix platform -----
// A deadline inside tokio's timer margin reaches `arm_at` only by bypassing `deadline_from`, which
// no real caller does. Debug builds assert; release builds wait unbounded.

#[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());
}

/// Release counterpart of the debug-assert test: the wait resolves with the future's own output,
/// reports an unbounded park, and no timer of any length bounds it.
#[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]);
}

/// The Windows registered waits are timed by the OS in real time: a tokio-clock deadline keeps its
/// remaining time, an expired one keeps none, and unbounded stays unbounded.
#[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); // virtual time ran ahead
    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);
}

/// A tokio-clock deadline the real clock would put inside the timer margin of `Instant`'s ceiling
/// is unbounded, as `deadline_from` makes it.
///
/// Mutant: the conversion adds the remaining time unchecked, or keeps a deadline inside the margin.
#[skuld::test]
fn to_real_clock_makes_a_deadline_inside_the_timer_margin_unbounded() {
    let tokio = std::time::Instant::now();
    let edge = crate::wait::instant_near_ceiling(tokio) - crate::wait::TOKIO_TIMER_ROUNDING_MARGIN;
    assert_eq!(super::to_real_clock_at(Some(edge), tokio, tokio), Some(edge));
    let later = tokio + Duration::from_nanos(1);
    assert_eq!(super::to_real_clock_at(Some(edge), tokio, later), None);
}

/// The wait runs on tokio's clock: virtual time advanced BEFORE the call must not eat the grace.
#[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 child = 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"
    );
}

/// Site 3 reads tokio's clock for "already expired": with virtual time far ahead of the real
/// clock, a deadline past on tokio's clock answers `MembersRemain` at once, without arming.
#[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!(crate::containment::drain_edge::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"),
    }
}

/// Site 2 reads tokio's clock for "already expired": a deadline past on tokio's clock probes at
/// once, arming nothing, even though the real clock still shows it in the future.
#[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 = crate::containment::drain_edge::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");
}

/// The thread a value was dropped on, reported when it drops.
struct DroppedOn(std::sync::mpsc::Sender<std::thread::ThreadId>);

impl Drop for DroppedOn {
    fn drop(&mut self) {
        _ = self.0.send(std::thread::current().id());
    }
}

/// The thread that dropped a [`DroppedOn`] that `on_blocking_pool` handed over after its task had
/// finished, and whose future was dropped before its next poll, on a runtime with one blocking
/// thread (held, so the first poll is `Pending` and the task finishes after it).
fn thread_that_dropped_a_finished_value() -> (std::thread::ThreadId, std::thread::ThreadId) {
    let (tx, dropped) = std::sync::mpsc::channel();
    let rt = crate::tokio::test_runtime::single_thread_pool_runtime();
    let (release, held) = std::sync::mpsc::channel::<()>();
    let hold = rt.spawn_blocking(move || held.recv());
    rt.block_on(async {
        let (waker, finished) = crate::tokio::test_runtime::counting_waker();
        let mut hop = Box::pin(super::on_blocking_pool("the value", move || DroppedOn(tx)));
        assert!(
            std::future::Future::poll(hop.as_mut(), &mut std::task::Context::from_waker(&waker)).is_pending(),
            "the hop is queued behind the held thread"
        );
        release.send(()).expect("release the held thread");
        finished.recv().expect("the task finished");
        drop(hop);
    });
    drop(hold);
    drop(rt);
    (
        std::thread::current().id(),
        dropped.recv().expect("the value was dropped"),
    )
}

/// A value whose drop can wait (a spawn's child) is dropped on the pool, not on the runtime thread
/// that drops the future.
///
/// Mutant: `Landing` drops a value it received on the dropping thread.
#[skuld::test]
fn a_finished_value_that_can_block_is_dropped_on_the_pool() {
    let (runtime_thread, dropped_on) = thread_that_dropped_a_finished_value();
    assert_ne!(dropped_on, runtime_thread, "dropped on the runtime thread");
}