agix-platform 0.4.4

Agix — this machine's execution providers, crash hook, and process identity
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
//! `LocalProcess` — a child process on this machine.
//!
//! On Unix every spawned program leads a session and a process group of its
//! own, with no controlling terminal, and stopping it signals the whole group:
//! a command is everything it started, not just the one pid `spawn` returned.
//! A [`GroupLedger`] remembers those groups past the handle, so whoever owns a
//! session can stop what its commands left running.

use futures::future::BoxFuture;
use futures::stream::BoxStream;
use futures::StreamExt;
use std::collections::BTreeSet;
use std::process::Stdio;
use std::sync::{Arc, Mutex};
use tokio::io::AsyncReadExt;
use tokio_util::sync::CancellationToken;

use base::interface::exec::{
    ExecError, ExitStatus, OutputChunk, OutputStream, Process, ProcessHandle, ProcessSpec,
    SubprocessEnv,
};

#[derive(Debug, Clone, Default)]
pub struct LocalProcess {
    env: SubprocessEnv,
    ledger: Option<Arc<GroupLedger>>,
}

impl LocalProcess {
    pub fn new(env: SubprocessEnv) -> Self {
        Self { env, ledger: None }
    }

    pub fn with_ledger(env: SubprocessEnv, ledger: Arc<GroupLedger>) -> Self {
        Self {
            env,
            ledger: Some(ledger),
        }
    }
}

#[derive(Debug, Default)]
pub struct GroupLedger {
    groups: Mutex<BTreeSet<i32>>,
}

impl GroupLedger {
    pub fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    /// Forgets the groups that have emptied first: a group id is reused once
    /// its group is gone, and a stale entry would one day signal a stranger.
    pub fn record(&self, group: i32) {
        let mut groups = self.groups.lock().unwrap_or_else(|e| e.into_inner());
        forget_emptied(&mut groups);
        groups.insert(group);
    }

    pub fn groups(&self) -> Vec<i32> {
        let mut groups = self.groups.lock().unwrap_or_else(|e| e.into_inner());
        forget_emptied(&mut groups);
        groups.iter().copied().collect()
    }

    pub async fn reap(&self, grace: std::time::Duration) {
        let targets: Vec<i32> = {
            let mut groups = self.groups.lock().unwrap_or_else(|e| e.into_inner());
            std::mem::take(&mut *groups)
                .into_iter()
                .filter(|g| group_alive(*g))
                .collect()
        };
        if targets.is_empty() {
            return;
        }
        let _forget = ForgetOnDrop(&targets);
        #[cfg(unix)]
        {
            for g in &targets {
                signal_group(*g, libc::SIGTERM);
            }
            let deadline = tokio::time::Instant::now() + grace;
            while tokio::time::Instant::now() < deadline && targets.iter().any(|g| group_alive(*g))
            {
                tokio::time::sleep(std::time::Duration::from_millis(20)).await;
            }
            for g in &targets {
                if group_alive(*g) {
                    signal_group(*g, libc::SIGKILL);
                }
            }
        }
        #[cfg(not(unix))]
        let _ = grace;
    }
}

fn forget_emptied(groups: &mut BTreeSet<i32>) {
    groups.retain(|g| {
        let alive = group_alive(*g);
        if !alive {
            crate::orphans::stopped(*g);
        }
        alive
    });
}

/// Takes the reaped groups off the process-wide list even if `reap` is
/// dropped while it waits out the grace period.
struct ForgetOnDrop<'a>(&'a [i32]);

impl Drop for ForgetOnDrop<'_> {
    fn drop(&mut self) {
        for g in self.0 {
            crate::orphans::stopped(*g);
        }
    }
}

#[cfg(unix)]
pub(crate) fn group_alive(group: i32) -> bool {
    // SAFETY: signal 0 only asks whether the group exists and is ours to signal.
    unsafe { libc::killpg(group, 0) == 0 }
}

#[cfg(not(unix))]
pub(crate) fn group_alive(_group: i32) -> bool {
    false
}

/// How long a stopped group gets to exit on `SIGTERM` before `SIGKILL`.
#[cfg(unix)]
const TERM_GRACE: std::time::Duration = std::time::Duration::from_millis(500);

#[async_trait::async_trait]
impl Process for LocalProcess {
    async fn spawn(
        &self,
        spec: ProcessSpec,
        cancel: CancellationToken,
    ) -> Result<Box<dyn ProcessHandle>, ExecError> {
        let mut cmd = tokio::process::Command::new(&spec.program);
        cmd.args(&spec.args)
            .current_dir(&spec.cwd)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(if spec.stdin.is_some() {
                Stdio::piped()
            } else {
                Stdio::null()
            });
        crate::env::apply_subprocess_env_in(&self.env, spec.env_scope, &mut cmd);
        for (k, v) in &spec.env {
            cmd.env(k, v);
        }
        // A handle that is dropped without being waited on must not leave a
        // process behind: cancellation drops the handle, and a leaked child
        // would keep writing to a pipe nobody reads.
        cmd.kill_on_drop(true);
        // Its own session, and so its own group: stopping the group reaches
        // the background processes it started, and with no controlling
        // terminal it cannot push input into the daemon's (`TIOCSTI` on
        // `/dev/tty`) for a shell outside any sandbox to run. The price is
        // that a terminal's Ctrl-C does not reach it directly; a host turns
        // Ctrl-C into cancellation, which does.
        #[cfg(unix)]
        // SAFETY: `setsid` is async-signal-safe and touches no memory.
        unsafe {
            cmd.pre_exec(|| {
                if libc::setsid() == -1 {
                    return Err(std::io::Error::last_os_error());
                }
                Ok(())
            });
        }

        let mut child = cmd
            .spawn()
            .map_err(|e| ExecError::failed(format!("{}: {e}", spec.program)))?;

        if let Some(bytes) = spec.stdin {
            if let Some(mut stdin) = child.stdin.take() {
                // Fed from a task of its own and closed when done: a child that
                // prints before it reads would otherwise fill its stdout pipe
                // while this call is still blocked writing, and a child reading
                // to EOF needs the pipe closed.
                tokio::spawn(async move {
                    use tokio::io::AsyncWriteExt;
                    let _ = stdin.write_all(&bytes).await;
                });
            }
        }

        #[cfg(unix)]
        let group = child.id().map(|pid| pid as libc::pid_t);
        #[cfg(unix)]
        if let Some(group) = group {
            crate::orphans::started(group);
            if let Some(ledger) = &self.ledger {
                ledger.record(group);
            }
        }
        #[cfg(unix)]
        let cancel_watch = group.map(|group| stop_on_cancel(group, cancel));
        #[cfg(not(unix))]
        drop(cancel);
        let stdout = child.stdout.take();
        let stderr = child.stderr.take();
        Ok(Box::new(LocalHandle {
            child,
            #[cfg(unix)]
            group,
            #[cfg(unix)]
            cancel_watch,
            kept: self.ledger.is_some(),
            output: Some(interleave(stdout, stderr)),
        }))
    }
}

/// Stops the group when `cancel` fires, for as long as the returned guard
/// (held by the handle) lives.
#[cfg(unix)]
fn stop_on_cancel(group: libc::pid_t, cancel: CancellationToken) -> tokio_util::sync::DropGuard {
    let handle_gone = CancellationToken::new();
    let watching = handle_gone.clone();
    tokio::spawn(async move {
        tokio::select! {
            _ = watching.cancelled() => {}
            _ = cancel.cancelled() => {
                signal_group(group, libc::SIGTERM);
                let deadline = tokio::time::Instant::now() + TERM_GRACE;
                while tokio::time::Instant::now() < deadline && group_alive(group) {
                    tokio::time::sleep(std::time::Duration::from_millis(20)).await;
                }
                signal_group(group, libc::SIGKILL);
            }
        }
    });
    handle_gone.drop_guard()
}

/// Both pipes as one tagged stream.
///
/// `select` rather than chaining, so a command that writes to stderr while
/// stdout is quiet is not held up behind it.
fn interleave(
    stdout: Option<tokio::process::ChildStdout>,
    stderr: Option<tokio::process::ChildStderr>,
) -> BoxStream<'static, Result<OutputChunk, ExecError>> {
    fn chunks<R: AsyncReadExt + Unpin + Send + 'static>(
        reader: Option<R>,
        stream: OutputStream,
    ) -> BoxStream<'static, Result<OutputChunk, ExecError>> {
        let Some(reader) = reader else {
            return futures::stream::empty().boxed();
        };
        // The state goes to `None` after a read error, which ends the stream.
        // Yielding the error and staying alive would hand a consumer that logs
        // and continues an endless supply of the same broken pipe.
        futures::stream::unfold(Some((reader, Vec::new())), move |state| async move {
            let (mut reader, mut buf) = state?;
            buf.resize(8192, 0);
            match reader.read(&mut buf).await {
                Ok(0) => None,
                Ok(n) => {
                    buf.truncate(n);
                    let chunk = OutputChunk {
                        stream,
                        bytes: std::mem::take(&mut buf),
                    };
                    Some((Ok(chunk), Some((reader, buf))))
                }
                Err(e) => Some((Err(ExecError::failed(e)), None)),
            }
        })
        .boxed()
    }
    futures::stream::select(
        chunks(stdout, OutputStream::Stdout),
        chunks(stderr, OutputStream::Stderr),
    )
    .boxed()
}

struct LocalHandle {
    child: tokio::process::Child,
    #[cfg(unix)]
    group: Option<libc::pid_t>,
    #[cfg(unix)]
    cancel_watch: Option<tokio_util::sync::DropGuard>,
    /// A ledger keeps the group past this handle and takes it off the
    /// process-wide list when it reaps it.
    kept: bool,
    output: Option<BoxStream<'static, Result<OutputChunk, ExecError>>>,
}

#[cfg(unix)]
pub(crate) fn signal_group(group: libc::pid_t, signal: libc::c_int) {
    // SAFETY: plain integers in, nothing borrowed; a group that is already
    // gone comes back as ESRCH, which is the outcome being asked for.
    unsafe {
        libc::killpg(group, signal);
    }
}

impl Drop for LocalHandle {
    fn drop(&mut self) {
        #[cfg(unix)]
        if let Some(group) = self.group {
            if matches!(self.child.try_wait(), Ok(None)) {
                signal_group(group, libc::SIGKILL);
            }
            if !self.kept {
                crate::orphans::stopped(group);
            }
        }
    }
}

impl ProcessHandle for LocalHandle {
    fn output(&mut self) -> Option<BoxStream<'static, Result<OutputChunk, ExecError>>> {
        self.output.take()
    }

    fn kill(&mut self) -> BoxFuture<'_, ()> {
        Box::pin(async move {
            #[cfg(unix)]
            if let Some(group) = self.group {
                signal_group(group, libc::SIGTERM);
                let _ = tokio::time::timeout(TERM_GRACE, self.child.wait()).await;
                signal_group(group, libc::SIGKILL);
            }
            let _ = self.child.kill().await;
        })
    }

    fn wait(&mut self) -> BoxFuture<'_, Result<ExitStatus, ExecError>> {
        Box::pin(async move {
            let s = self.child.wait().await.map_err(ExecError::failed)?;
            #[cfg(unix)]
            if self.group.is_some_and(|group| !group_alive(group)) {
                self.cancel_watch = None;
            }
            Ok(ExitStatus {
                code: s.code(),
                success: s.success(),
            })
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    async fn run(spec: ProcessSpec) -> (String, String, ExitStatus) {
        run_with(LocalProcess::default(), spec).await
    }

    async fn run_with(process: LocalProcess, spec: ProcessSpec) -> (String, String, ExitStatus) {
        let mut h = process.spawn(spec, CancellationToken::new()).await.unwrap();
        let mut out = h.output().expect("first call yields the stream");
        let (mut o, mut e) = (Vec::new(), Vec::new());
        while let Some(chunk) = out.next().await {
            let c = chunk.unwrap();
            match c.stream {
                OutputStream::Stdout => o.extend(c.bytes),
                OutputStream::Stderr => e.extend(c.bytes),
            }
        }
        let status = h.wait().await.unwrap();
        (
            String::from_utf8_lossy(&o).into_owned(),
            String::from_utf8_lossy(&e).into_owned(),
            status,
        )
    }

    fn sh(command: &str) -> ProcessSpec {
        ProcessSpec::new("bash", std::env::temp_dir()).args(["-c".to_string(), command.to_string()])
    }

    #[tokio::test]
    async fn both_pipes_arrive_tagged_and_the_exit_status_comes_back() {
        let (out, err, status) = run(sh("echo hi; echo bad >&2; exit 3")).await;
        assert_eq!(out.trim(), "hi");
        assert_eq!(err.trim(), "bad");
        assert_eq!(status.code, Some(3));
        assert!(!status.success);
    }

    #[tokio::test]
    async fn the_stream_is_taken_once() {
        let mut h = LocalProcess::default()
            .spawn(sh("true"), CancellationToken::new())
            .await
            .unwrap();
        assert!(h.output().is_some());
        assert!(h.output().is_none(), "the stream owns the pipes");
        let _ = h.wait().await;
    }

    #[tokio::test]
    async fn stdin_reaches_the_child_and_then_ends() {
        let mut spec = sh("cat");
        spec.stdin = Some(b"fed in".to_vec());
        let (out, _, status) = run(spec).await;
        assert_eq!(out, "fed in");
        assert!(
            status.success,
            "a child reading to EOF has to see the pipe close"
        );
    }

    /// Output arrives while the process is still running, which is the
    /// property a whole-output provider would silently remove.
    #[tokio::test]
    async fn output_arrives_before_the_process_exits() {
        let mut h = LocalProcess::default()
            .spawn(
                sh("echo first; sleep 5; echo never"),
                CancellationToken::new(),
            )
            .await
            .unwrap();
        let mut out = h.output().unwrap();
        let first = tokio::time::timeout(std::time::Duration::from_secs(2), out.next())
            .await
            .expect("the first chunk must not wait for the exit")
            .unwrap()
            .unwrap();
        assert_eq!(String::from_utf8_lossy(&first.bytes).trim(), "first");
        h.kill().await;
    }

    #[tokio::test]
    async fn a_minimal_spec_starts_from_what_a_shell_needs_and_its_own_variables() {
        if std::env::var_os("CARGO_MANIFEST_DIR").is_none() {
            return;
        }
        let mut spec = sh(
            "printenv CARGO_MANIFEST_DIR; printenv PATH >/dev/null && echo has-path; printenv OWN",
        );
        spec.env_scope = base::interface::exec::EnvScope::Minimal;
        spec.env.push(("OWN".into(), "mine".into()));
        let (out, _, _) = run(spec).await;
        assert!(!out.contains(env!("CARGO_MANIFEST_DIR")), "{out}");
        assert!(out.contains("has-path"), "{out}");
        assert!(out.contains("mine"), "{out}");
    }

    #[tokio::test]
    async fn the_environment_policy_reaches_the_child() {
        // `cargo test` runs the test binary with this set; under anything
        // else there is nothing to observe.
        if std::env::var_os("CARGO_MANIFEST_DIR").is_none() {
            return;
        }
        let probe = || sh("printenv CARGO_MANIFEST_DIR; printenv PATH >/dev/null && echo has-path");
        let (inherited, _, _) = run(probe()).await;
        assert!(inherited.contains(env!("CARGO_MANIFEST_DIR")));

        let allowlist = SubprocessEnv {
            mode: base::interface::exec::SubprocessEnvMode::Allowlist,
            allow: vec![],
        };
        let (out, _, _) = run_with(LocalProcess::new(allowlist), probe()).await;
        assert_eq!(out.trim(), "has-path");
    }

    #[cfg(unix)]
    async fn gone_within(pid: libc::pid_t, limit: std::time::Duration) -> bool {
        let deadline = std::time::Instant::now() + limit;
        while std::time::Instant::now() < deadline {
            // SAFETY: signal 0 only asks whether the pid exists.
            if unsafe { libc::kill(pid, 0) } != 0 {
                return true;
            }
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        }
        false
    }

    #[cfg(unix)]
    async fn first_line(out: &mut BoxStream<'static, Result<OutputChunk, ExecError>>) -> String {
        let chunk = tokio::time::timeout(std::time::Duration::from_secs(5), out.next())
            .await
            .expect("the background pid is printed straight away")
            .unwrap()
            .unwrap();
        String::from_utf8_lossy(&chunk.bytes).trim().to_string()
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn kill_takes_the_background_children_with_it() {
        let mut h = LocalProcess::default()
            .spawn(sh("sleep 300 & echo $!; wait"), CancellationToken::new())
            .await
            .unwrap();
        let mut out = h.output().unwrap();
        let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
        h.kill().await;
        assert!(
            gone_within(pid, std::time::Duration::from_secs(3)).await,
            "the background sleep outlived the kill"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn kill_after_exit_still_reaches_what_was_left_running() {
        let mut h = LocalProcess::default()
            .spawn(sh("sleep 300 & echo $!"), CancellationToken::new())
            .await
            .unwrap();
        let mut out = h.output().unwrap();
        let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
        assert!(h.wait().await.unwrap().success);
        h.kill().await;
        assert!(
            gone_within(pid, std::time::Duration::from_secs(3)).await,
            "the orphaned sleep survived a kill issued after its parent exited"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn the_ledger_reaps_what_a_finished_command_left_running() {
        let ledger = GroupLedger::new();
        let process = LocalProcess::with_ledger(SubprocessEnv::default(), ledger.clone());
        let mut h = process
            .spawn(
                sh("sleep 300 >/dev/null 2>&1 & echo $!"),
                CancellationToken::new(),
            )
            .await
            .unwrap();
        let mut out = h.output().unwrap();
        let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
        assert!(h.wait().await.unwrap().success);
        drop(out);
        drop(h);
        assert!(
            !gone_within(pid, std::time::Duration::from_millis(200)).await,
            "dropping a finished handle leaves the background sleep alone"
        );
        assert_eq!(ledger.groups().len(), 1, "the group is still on record");

        ledger.reap(std::time::Duration::from_millis(500)).await;
        let reaped = gone_within(pid, std::time::Duration::from_secs(3)).await;
        if !reaped {
            unsafe { libc::kill(pid, libc::SIGKILL) };
        }
        assert!(reaped, "reap stops the background sleep");
        assert!(ledger.groups().is_empty());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn an_emptied_group_drops_off_the_ledger() {
        let ledger = GroupLedger::new();
        let process = LocalProcess::with_ledger(SubprocessEnv::default(), ledger.clone());
        let (_, _, status) = run_with(process, sh("true")).await;
        assert!(status.success);
        assert!(ledger.groups().is_empty(), "{:?}", ledger.groups());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn cancelling_the_spawn_token_stops_the_whole_group() {
        let cancel = CancellationToken::new();
        let mut h = LocalProcess::default()
            .spawn(sh("sleep 300 & echo $!; wait"), cancel.clone())
            .await
            .unwrap();
        let mut out = h.output().unwrap();
        let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
        cancel.cancel();
        let stopped = gone_within(pid, std::time::Duration::from_secs(3)).await;
        if !stopped {
            unsafe { libc::kill(pid, libc::SIGKILL) };
        }
        assert!(stopped, "the background sleep outlived the cancellation");
        assert!(!h.wait().await.unwrap().success);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn dropping_a_running_handle_stops_the_whole_group() {
        let mut h = LocalProcess::default()
            .spawn(sh("sleep 300 & echo $!; wait"), CancellationToken::new())
            .await
            .unwrap();
        let mut out = h.output().unwrap();
        let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
        drop(h);
        assert!(gone_within(pid, std::time::Duration::from_secs(3)).await);
    }

    /// Once the group is gone its id can belong to someone else, so the
    /// handle stops watching for cancellation.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_finished_group_is_no_longer_watched() {
        let mut h = LocalProcess::default()
            .spawn(sh("true"), CancellationToken::new())
            .await
            .unwrap();
        let mut out = h.output().unwrap();
        while out.next().await.is_some() {}
        assert!(h.wait().await.unwrap().success);
        for _ in 0..10 {
            tokio::task::yield_now().await;
        }
        let alive = tokio::runtime::Handle::current()
            .metrics()
            .num_alive_tasks();
        assert_eq!(alive, 0, "the cancellation watcher outlived the group");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_group_that_outlives_its_leader_is_still_stopped_on_cancel() {
        let cancel = CancellationToken::new();
        let mut h = LocalProcess::default()
            .spawn(sh("sleep 300 & echo $!"), cancel.clone())
            .await
            .unwrap();
        let mut out = h.output().unwrap();
        let pid: libc::pid_t = first_line(&mut out).await.parse().unwrap();
        assert!(h.wait().await.unwrap().success);
        cancel.cancel();
        let stopped = gone_within(pid, std::time::Duration::from_secs(3)).await;
        if !stopped {
            unsafe { libc::kill(pid, libc::SIGKILL) };
        }
        assert!(stopped, "the background sleep outlived the cancellation");
    }
}