local-ci 0.20.0

Run the GitHub Actions jobs a branch would trigger, locally, in an isolated worktree, and print a short report
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
//! Bounded, attempt-owned Docker control and cleanup. No global discovery or fallback.
use crate::context::ExecContext;
use anyhow::{bail, Context, Result};
use std::io::Read;
use std::os::fd::AsRawFd;
use std::os::unix::process::CommandExt;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

const MAX_OUTPUT: usize = 64 * 1024;

/// A cleanup failure is an environment diagnostic, not a failing test.
#[derive(Debug)]
pub(crate) struct CleanupIncomplete(pub(crate) String);

impl std::fmt::Display for CleanupIncomplete {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "cleanup incomplete: {}", self.0)
    }
}

// Keep the leader unreaped until its entire group has been signalled. Owning
// this unreaped Child pins its PID/start identity, including after it exits;
// there is no PID lookup/reuse window. Never signal a caller-provided group.
pub(crate) struct OwnedGroup(pub(crate) Child, pub(crate) crate::context::CancelHandle);
impl Drop for OwnedGroup {
    fn drop(&mut self) {
        let pid = self.0.id() as i32;
        let mut state: libc::siginfo_t = unsafe { std::mem::zeroed() };
        let owned = loop {
            let result = unsafe {
                libc::waitid(
                    libc::P_PID,
                    self.0.id(),
                    &mut state,
                    libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
                )
            };
            if result == 0 {
                break true;
            }
            if std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted {
                break false;
            }
        };
        if pid > 1 && owned {
            // No signal or wait follows a known lost/reaped identity.
            unsafe {
                libc::killpg(pid, libc::SIGKILL);
            }
            if self.0.wait().is_err() {
                self.1.record_native_uncertain(pid as u32);
            } else {
                let exists = unsafe { libc::killpg(pid, 0) };
                if exists == 0
                    || std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
                {
                    self.1.record_native_uncertain(pid as u32);
                }
            }
        } else {
            self.1.record_native_uncertain(pid as u32);
        }
    }
}

/// Control commands stop promptly when the attempt is cancelled. Cleanup
/// commands use the same runner but must still run after cancellation.
pub(crate) fn docker_control(
    ctx: &ExecContext,
    args: &[&str],
    timeout: Duration,
) -> Result<Vec<u8>> {
    docker_with_cancel(ctx, args, timeout, true)
}

fn docker(ctx: &ExecContext, args: &[&str], timeout: Duration) -> Result<Vec<u8>> {
    docker_with_cancel(ctx, args, timeout, false)
}

fn docker_with_cancel(
    ctx: &ExecContext,
    args: &[&str],
    timeout: Duration,
    stop_on_cancel: bool,
) -> Result<Vec<u8>> {
    if stop_on_cancel && ctx.cancel.is_cancelled() {
        bail!("control command cancelled");
    }
    let mut command = ctx.command("docker");
    command.args(args);
    bounded_command(ctx, command, timeout, stop_on_cancel)
}

/// One bounded owned control command, used by Docker and port release only.
/// Reaping this process proves no state change in an external daemon by itself.
pub(crate) fn bounded_command(
    ctx: &ExecContext,
    mut command: Command,
    timeout: Duration,
    stop_on_cancel: bool,
) -> Result<Vec<u8>> {
    if stop_on_cancel && ctx.cancel.is_cancelled() {
        bail!("control command cancelled");
    }
    #[cfg(test)]
    let observed: Vec<String> = command
        .get_args()
        .map(|s| s.to_string_lossy().into_owned())
        .collect();
    let mut child = OwnedGroup(
        command
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .process_group(0)
            .spawn()
            .context("start control command")?,
        ctx.cancel.clone(),
    );
    #[cfg(test)]
    tests::observe_spawn(
        &child.0,
        &observed.iter().map(String::as_str).collect::<Vec<_>>(),
        timeout,
    );
    let mut stdout = child.0.stdout.take().context("missing stdout")?;
    let mut stderr = child.0.stderr.take().context("missing stderr")?;
    for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] {
        // SAFETY: both descriptors are owned pipes with independent read ends.
        unsafe {
            let flags = libc::fcntl(fd, libc::F_GETFL);
            if flags < 0 || libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {
                return Err(std::io::Error::last_os_error()).context("nonblocking control pipe");
            }
        }
    }
    let started = Instant::now();
    let mut output = Vec::new();
    let mut errors = Vec::new();
    let mut eof = [false; 2];
    loop {
        if stop_on_cancel && ctx.cancel.is_cancelled() {
            bail!("control command cancelled");
        }
        if started.elapsed() >= timeout {
            bail!("control command deadline exceeded");
        }
        for (i, (pipe, bytes)) in [
            (&mut stdout as &mut dyn Read, &mut output),
            (&mut stderr as &mut dyn Read, &mut errors),
        ]
        .into_iter()
        .enumerate()
        {
            let mut buf = [0; 4096];
            // One read per stream per tick: a continuous writer cannot starve
            // the other stream or the deadline check.
            match pipe.read(&mut buf) {
                Ok(0) => eof[i] = true,
                Ok(n) => {
                    if bytes.len() + n > MAX_OUTPUT {
                        bail!("control command output limit exceeded");
                    }
                    bytes.extend_from_slice(&buf[..n]);
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => (),
                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => (),
                Err(e) => return Err(e).context("read control command output"),
            }
        }
        let mut status: libc::siginfo_t = unsafe { std::mem::zeroed() };
        // SAFETY: inspect only our owned child without reaping it. Drop kills
        // descendants before wait releases the leader's PID identity.
        let rc = unsafe {
            libc::waitid(
                libc::P_PID,
                child.0.id(),
                &mut status,
                libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
            )
        };
        if rc != 0 {
            return Err(std::io::Error::last_os_error()).context("inspect control child");
        }
        if unsafe { status.si_pid() } != 0 && eof.iter().all(|v| *v) {
            if status.si_code != libc::CLD_EXITED || unsafe { status.si_status() } != 0 {
                // Do not expose daemon stderr, which can contain credentials.
                bail!("control command exited unsuccessfully");
            }
            return Ok(output);
        }
        std::thread::sleep(Duration::from_millis(5));
    }
}

/// Only complete IDs acknowledged by this attempt's create are accepted.
/// Queries are filtered by that exact immutable ID; there is no global discovery
/// or fallback from an unknown creation name to a deletion.
pub(crate) fn remove_tracked_containers(
    ctx: &ExecContext,
    names: &[String],
) -> Vec<CleanupIncomplete> {
    remove_tracked_with_timeout(ctx, names, Duration::from_secs(30))
}

fn remove_tracked_with_timeout(
    ctx: &ExecContext,
    names: &[String],
    timeout: Duration,
) -> Vec<CleanupIncomplete> {
    if names.is_empty() {
        return vec![];
    }
    if names.iter().any(|id| !valid_container_id(id)) {
        return vec![CleanupIncomplete("invalid tracked container ID".into())];
    }
    let deadline = Instant::now() + timeout;
    for id in names {
        let result = (|| -> Result<()> {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                bail!("container cleanup deadline exceeded");
            }
            let filter = format!("id={id}");
            let bytes = docker(
                ctx,
                &["ps", "-aq", "--no-trunc", "--filter", &filter],
                remaining.min(Duration::from_secs(5)),
            )?;
            let found = std::str::from_utf8(&bytes).context("invalid container ID encoding")?;
            let ids: Vec<&str> = found.lines().collect();
            if ids.iter().any(|other| *other != id) || ids.len() > 1 {
                bail!("unexpected container ID in exact filtered query");
            }
            if !ids.is_empty() {
                let remaining = deadline.saturating_duration_since(Instant::now());
                if remaining.is_zero() {
                    bail!("container cleanup deadline exceeded");
                }
                docker(ctx, &["rm", "-f", "--", id], remaining)?;
            }
            Ok(())
        })();
        if let Err(error) = result {
            return vec![CleanupIncomplete(format!(
                "remove tracked containers: {error:#}"
            ))];
        }
    }
    vec![]
}

pub(crate) fn valid_container_id(id: &str) -> bool {
    id.len() == 64
        && id
            .bytes()
            .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
}

pub(crate) fn compose_down(ctx: &ExecContext, projects: &[String]) -> Vec<CleanupIncomplete> {
    compose_down_with_budgets(
        ctx,
        projects,
        Duration::from_secs(5),
        Duration::from_secs(30),
    )
}

#[cfg(test)]
fn compose_down_with_timeout(
    ctx: &ExecContext,
    projects: &[String],
    timeout: Duration,
) -> Vec<CleanupIncomplete> {
    compose_down_with_budgets(ctx, projects, timeout, timeout)
}

fn compose_down_with_budgets(
    ctx: &ExecContext,
    projects: &[String],
    query_timeout: Duration,
    action_timeout: Duration,
) -> Vec<CleanupIncomplete> {
    let mut failures = Vec::new();
    for (index, project) in projects.iter().enumerate() {
        let result = (|| -> Result<()> {
            // Compose's documented project grammar. Validate before building
            // argv or invoking Docker, even though projects come from our run.
            if project.is_empty()
                || project.len() > 255
                || !project.as_bytes()[0].is_ascii_lowercase()
                    && !project.as_bytes()[0].is_ascii_digit()
                || !project
                    .bytes()
                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
            {
                bail!("invalid Compose project name");
            }
            let label = format!("label=com.docker.compose.project={project}");
            let bytes = docker(ctx, &["ps", "-aq", "--filter", &label], query_timeout)
                .context("query owned Compose containers")?;
            let ids = std::str::from_utf8(&bytes).context("invalid container ID encoding")?;
            for id in ids.lines() {
                if !matches!(id.len(), 12 | 64)
                    || !id
                        .bytes()
                        .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
                {
                    bail!("invalid container ID list");
                }
            }
            if !ids.is_empty() {
                docker(
                    ctx,
                    &["compose", "-p", project, "down", "--remove-orphans"],
                    action_timeout,
                )
                .context("take down owned Compose project")?;
            }
            Ok(())
        })();
        if let Err(e) = result {
            failures.push(CleanupIncomplete(format!("{e:#}")));
            // A broken/unavailable daemon must not cost one deadline per
            // project. Every skipped project remains explicitly incomplete.
            for _ in &projects[index + 1..] {
                failures.push(CleanupIncomplete(
                    "project not attempted after an earlier cleanup failure".into(),
                ));
            }
            break;
        }
    }
    failures
}

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

    // Parent-owned receipts do not depend on the stub being scheduled before
    // a short deadline. Selected adversarial fixtures additionally establish
    // their causal state before the production runtime budget starts.
    struct SpawnReceipt {
        pid: i32,
        args: Vec<String>,
        started: Instant,
        timeout: Duration,
    }
    type SpawnObserver = Box<dyn FnMut(&Child, &[&str], Duration)>;
    std::thread_local! {
        static OBSERVER: std::cell::RefCell<Option<SpawnObserver>> = const { std::cell::RefCell::new(None) };
    }
    pub(super) fn observe_spawn(child: &Child, args: &[&str], timeout: Duration) {
        OBSERVER.with_borrow_mut(|observer| {
            if let Some(observer) = observer {
                observer(child, args, timeout);
            }
        });
    }
    fn observed<T>(
        ready: Option<(String, std::path::PathBuf, bool)>,
        run: impl FnOnce() -> T,
    ) -> (T, Vec<SpawnReceipt>) {
        let receipts = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
        let recorded = receipts.clone();
        OBSERVER.with_borrow_mut(|observer| {
            assert!(observer.is_none());
            *observer = Some(Box::new(move |child, args, timeout| {
                if let Some((phase, marker, wait_for_exit)) = &ready {
                    if args.first() == Some(&phase.as_str()) {
                        let setup = Instant::now();
                        while !marker.exists() {
                            assert!(
                                setup.elapsed() < Duration::from_secs(10),
                                "stub startup marker missing"
                            );
                            std::thread::sleep(Duration::from_millis(5));
                        }
                    }
                    if args.first() != Some(&phase.as_str()) || *wait_for_exit {
                        // The prerequisite query must complete before testing
                        // the down phase's deadline, even on a busy scheduler.
                        let setup = Instant::now();
                        loop {
                            let mut status: libc::siginfo_t = unsafe { std::mem::zeroed() };
                            let rc = unsafe {
                                libc::waitid(
                                    libc::P_PID,
                                    child.id(),
                                    &mut status,
                                    libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
                                )
                            };
                            assert_eq!(rc, 0);
                            if unsafe { status.si_pid() } != 0 {
                                break;
                            }
                            assert!(
                                setup.elapsed() < Duration::from_secs(10),
                                "prerequisite stub did not exit"
                            );
                            std::thread::sleep(Duration::from_millis(5));
                        }
                    }
                }
                recorded.borrow_mut().push(SpawnReceipt {
                    pid: child.id() as i32,
                    args: args.iter().map(|arg| (*arg).to_owned()).collect(),
                    started: Instant::now(),
                    timeout,
                });
            }));
        });
        struct Reset;
        impl Drop for Reset {
            fn drop(&mut self) {
                OBSERVER.with_borrow_mut(|observer| *observer = None);
            }
        }
        let reset = Reset;
        let result = run();
        drop(reset);
        (
            result,
            std::rc::Rc::try_unwrap(receipts).ok().unwrap().into_inner(),
        )
    }

    fn fixture(script: &str) -> (tempfile::TempDir, ExecContext) {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("docker");
        crate::fake_exec::write_executable(
            &file,
            format!("#!/bin/sh\necho \"$*\" >> \"$HOME/calls\"\n{script}\n"),
            0o755,
        );
        let ctx = ExecContext::new(
            [
                ("HOME".into(), dir.path().display().to_string()),
                (
                    "PATH".into(),
                    format!("{}:/usr/bin:/bin", dir.path().display()),
                ),
            ]
            .into_iter()
            .collect(),
        );
        (dir, ctx)
    }
    fn run(ctx: &ExecContext) -> Vec<CleanupIncomplete> {
        // Normal behavior is not a subprocess-startup benchmark. Explicit timeout
        // fixtures below keep their short deadline and reaping assertions.
        compose_down_with_timeout(ctx, &["owned-project".into()], Duration::from_secs(2))
    }
    fn calls(dir: &tempfile::TempDir) -> String {
        std::fs::read_to_string(dir.path().join("calls")).unwrap_or_default()
    }
    #[test]
    fn control_cancel_is_prompt_and_reaps_owned_child_but_cleanup_still_runs() {
        let (dir, ctx) = fixture("echo $$ > \"$HOME/pid\"; exec sleep 20");
        let cancel = ctx.cancel.clone();
        let ready = dir.path().join("pid");
        let signal = std::thread::spawn(move || {
            let start = Instant::now();
            while !ready.exists() {
                assert!(
                    start.elapsed() < Duration::from_secs(10),
                    "stub startup marker missing"
                );
                std::thread::sleep(Duration::from_millis(5));
            }
            let cancelled = Instant::now();
            cancel.cancel();
            cancelled
        });
        let (result, receipts) = observed(None, || {
            docker_control(&ctx, &["info"], Duration::from_secs(20))
        });
        let cancelled = signal.join().unwrap();
        assert!(result.unwrap_err().to_string().contains("cancelled"));
        assert!(cancelled.elapsed() < Duration::from_secs(3));
        assert_eq!(receipts.len(), 1);
        let pid = receipts[0].pid;
        assert_eq!(
            unsafe { libc::waitpid(pid, std::ptr::null_mut(), libc::WNOHANG) },
            -1
        );
        assert_eq!(
            std::io::Error::last_os_error().raw_os_error(),
            Some(libc::ECHILD)
        );
        crate::fake_exec::write_executable(
            &dir.path().join("docker"),
            "#!/bin/sh\necho \"$*\" >> \"$HOME/calls\"\nif [ \"$1\" = ps ]; then for arg do case \"$arg\" in id=*) echo \"${arg#id=}\";; esac; done; fi\nexit 0\n",
            0o755,
        );
        assert!(docker_control(&ctx, &["logs"], Duration::from_millis(250)).is_err());
        assert!(!calls(&dir).lines().any(|line| line == "logs"));
        assert!(run(&ctx).is_empty());
        assert!(
            remove_tracked_with_timeout(&ctx, &["a".repeat(64)], Duration::from_secs(2)).is_empty()
        );
        assert!(calls(&dir).contains(&format!("rm -f -- {}", "a".repeat(64))));
    }

    #[test]
    fn tracked_removal_validates_scope_and_reports_blockage_and_failure() {
        let (dir, ctx) = fixture("if [ \"$1\" = ps ]; then for arg do case \"$arg\" in id=*) echo \"${arg#id=}\";; esac; done; fi\nexit 0");
        assert!(remove_tracked_with_timeout(&ctx, &[], Duration::from_millis(250)).is_empty());
        assert!(calls(&dir).is_empty());
        for name in ["", "--all", "one two", "a\n", &"a".repeat(256)] {
            assert!(
                !remove_tracked_with_timeout(&ctx, &[name.into()], Duration::from_millis(250))
                    .is_empty()
            );
        }
        assert!(calls(&dir).is_empty());
        assert!(remove_tracked_with_timeout(
            &ctx,
            &["a".repeat(64), "b".repeat(64)],
            Duration::from_secs(2)
        )
        .is_empty());
        assert_eq!(calls(&dir), format!("ps -aq --no-trunc --filter id={}\nrm -f -- {}\nps -aq --no-trunc --filter id={}\nrm -f -- {}\n", "a".repeat(64), "a".repeat(64), "b".repeat(64), "b".repeat(64)));
        for script in ["exec sleep 20", "echo secret-daemon-error >&2; exit 1"] {
            let (_dir, ctx) = fixture(script);
            let errors =
                remove_tracked_with_timeout(&ctx, &["a".repeat(64)], Duration::from_millis(250));
            assert_eq!(errors.len(), 1);
            assert!(errors[0].to_string().contains("remove tracked"));
            assert!(!errors[0].to_string().contains("secret-daemon-error"));
        }
    }

    #[test]
    fn control_drains_both_pipes_and_keeps_daemon_errors_private() {
        let (_dir, ctx) = fixture("(dd if=/dev/zero bs=32768 count=1 2>/dev/null) >&2\n(dd if=/dev/zero bs=32768 count=1 2>/dev/null)");
        assert_eq!(
            docker_control(&ctx, &["logs"], Duration::from_secs(2))
                .unwrap()
                .len(),
            32768
        );
        let (_dir, ctx) = fixture("echo daemon-private >&2; echo partial; exit 1");
        let error = docker_control(&ctx, &["inspect"], Duration::from_secs(2)).unwrap_err();
        assert!(!format!("{error:#}").contains("daemon-private"));
        let (_dir, ctx) =
            fixture("while :; do printf 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' >&2; done");
        assert!(docker_control(&ctx, &["logs"], Duration::from_secs(2))
            .unwrap_err()
            .to_string()
            .contains("output limit"));
    }

    #[test]
    fn cancellation_handle_removes_only_tracked_names_even_after_cancel() {
        let (dir, ctx) = fixture("if [ \"$1\" = ps ]; then for arg do case \"$arg\" in id=*) echo \"${arg#id=}\";; esac; done; fi\nexit 0");
        ctx.cancel.track_container("a".repeat(64));
        ctx.cancel.track_container("b".repeat(64));
        ctx.cancel.cancel();
        ctx.cancel.remove_containers(&ctx);
        assert_eq!(calls(&dir), format!("ps -aq --no-trunc --filter id={}\nrm -f -- {}\nps -aq --no-trunc --filter id={}\nrm -f -- {}\n", "a".repeat(64), "a".repeat(64), "b".repeat(64), "b".repeat(64)));
        ctx.cancel.remove_containers(&ctx);
        assert_eq!(calls(&dir).lines().count(), 4);
    }

    #[test]
    fn cleanup_normal_and_empty() {
        for ids in [
            "",
            "012345abcdef",
            "012345abcdef\nabcdef012345",
            &"a".repeat(64),
        ] {
            let (dir, ctx) = fixture(&format!("[ \"$1\" = ps ] && printf '%s' '{ids}'\nexit 0"));
            let errors = run(&ctx);
            assert!(errors.is_empty(), "{errors:?}");
            let log = calls(&dir);
            assert!(
                log.starts_with("ps -aq --filter label=com.docker.compose.project=owned-project\n")
            );
            assert_eq!(
                log.contains("compose -p owned-project down --remove-orphans"),
                !ids.is_empty()
            );
        }
    }
    #[test]
    fn cleanup_refuses_bad_ids_partial_nonzero_and_excessive_output() {
        for script in [
            "printf '012345abcdef\n'; exit 1",
            "kill -TERM $$",
            "echo invalid",
            "echo 012345abcdeF",
            "printf '\\377'",
            "printf '012345abcdef\n\n'",
            "printf ' '; exit 0",
            "while :; do printf 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; done",
            "while :; do printf 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' >&2; done",
        ] {
            let (dir, ctx) = fixture(script);
            assert!(!run(&ctx).is_empty(), "{script}");
            assert!(
                !calls(&dir).lines().any(|line| line.starts_with("compose ")),
                "{script}"
            );
        }
    }
    #[test]
    fn cleanup_refuses_invalid_projects_without_invoking_docker() {
        let (dir, ctx) = fixture("exit 0");
        for project in ["", "--help", "A", "a b", "a\n", &"a".repeat(256)] {
            assert!(!compose_down_with_timeout(
                &ctx,
                &[project.into()],
                Duration::from_millis(250)
            )
            .is_empty());
        }
        assert!(calls(&dir).is_empty());
    }
    #[test]
    fn cleanup_bounds_blocked_query_and_down_and_reaps_owned_leader() {
        for phase in ["ps", "compose"] {
            let (dir, ctx) = fixture(&format!(
                "if [ \"$1\" = {phase} ]; then sleep 0.35; echo $$ > \"$HOME/pid\"; exec sleep 20; fi\necho 012345abcdef"));
            let (errors, receipts) =
                observed(Some((phase.into(), dir.path().join("pid"), false)), || {
                    compose_down_with_timeout(
                        &ctx,
                        &["owned-project".into()],
                        Duration::from_millis(250),
                    )
                });
            assert_eq!(errors.len(), 1);
            assert!(errors[0].to_string().contains("deadline"));
            let blocked = receipts.last().unwrap();
            assert_eq!(blocked.args[0], phase);
            assert!(blocked.started.elapsed() < Duration::from_secs(3));
            if phase == "ps" {
                assert!(!calls(&dir).lines().any(|line| line.starts_with("compose ")));
            }
            let pid = blocked.pid;
            // waitpid is read-only here: ECHILD proves the helper already reaped it.
            assert_eq!(
                unsafe { libc::waitpid(pid, std::ptr::null_mut(), libc::WNOHANG) },
                -1
            );
            assert_eq!(
                std::io::Error::last_os_error().raw_os_error(),
                Some(libc::ECHILD)
            );
        }
    }
    #[test]
    fn cleanup_bounds_inherited_pipe_after_leader_exits() {
        let (dir, ctx) = fixture("sleep 0.35; sleep 20 &\necho $! > \"$HOME/plugin\"\nexit 0");
        let (errors, receipts) =
            observed(Some(("ps".into(), dir.path().join("plugin"), true)), || {
                compose_down_with_timeout(
                    &ctx,
                    &["owned-project".into()],
                    Duration::from_millis(250),
                )
            });
        assert!(!errors.is_empty());
        assert_eq!(receipts.len(), 1);
        assert!(receipts[0].started.elapsed() < Duration::from_secs(3));
        assert!(!calls(&dir).lines().any(|line| line.starts_with("compose ")));
        // The leader exits before the timeout, but stays unreaped until the
        // helper kills its owned process group, including its pipe holder.
        let pid = std::fs::read_to_string(dir.path().join("plugin")).unwrap();
        let status = ctx
            .command("ps")
            .args(["-p", pid.trim(), "-o", "stat="])
            .output()
            .unwrap();
        // An orphan can briefly remain as a zombie until the OS reaps it;
        // it must no longer be an executing pipe holder.
        assert!(
            !status.status.success()
                || String::from_utf8_lossy(&status.stdout)
                    .trim()
                    .starts_with('Z')
        );
    }
    #[test]
    fn cleanup_output_limit_is_inclusive_on_both_streams() {
        for redirect in ["", ">&2"] {
            for count in [MAX_OUTPUT, MAX_OUTPUT + 1] {
                let (_dir, ctx) = fixture(&format!(
                    "(dd if=/dev/zero bs={count} count=1 2>/dev/null) {redirect}"
                ));
                let result = docker(&ctx, &["ps"], Duration::from_secs(2));
                if count == MAX_OUTPUT {
                    let output = result.unwrap();
                    assert_eq!(output.len(), if redirect.is_empty() { count } else { 0 });
                } else {
                    assert!(result.unwrap_err().to_string().contains("output limit"));
                }
            }
        }
    }
    #[test]
    fn cleanup_selects_shorter_read_only_budget_and_preserves_action_budget() {
        let (_dir, ctx) = fixture("[ \"$1\" = ps ] && echo 012345abcdef; exit 0");
        let (errors, receipts) = observed(None, || compose_down(&ctx, &["owned-project".into()]));
        assert!(errors.is_empty());
        assert_eq!(receipts.len(), 2);
        assert_eq!(receipts[0].args[0], "ps");
        assert_eq!(receipts[0].timeout, Duration::from_secs(5));
        assert_eq!(receipts[1].args[0], "compose");
        assert_eq!(receipts[1].timeout, Duration::from_secs(30));
        let (errors, receipts) = observed(None, || run(&ctx));
        assert!(errors.is_empty());
        assert_eq!(receipts.len(), 2);
        assert!(receipts
            .iter()
            .all(|receipt| receipt.timeout == Duration::from_secs(2)));
    }

    #[test]
    fn cleanup_failure_marks_unattempted_projects_without_more_queries() {
        let (_dir, ctx) = fixture("exit 1");
        let (failures, receipts) = observed(None, || {
            compose_down_with_timeout(
                &ctx,
                &["one".into(), "two".into(), "three".into()],
                Duration::from_millis(250),
            )
        });
        assert_eq!(failures.len(), 3);
        assert!(failures[1].to_string().contains("not attempted"));
        assert!(failures[2].to_string().contains("not attempted"));
        assert_eq!(receipts.len(), 1);
        assert_eq!(receipts[0].args[0], "ps");
    }
    #[test]
    fn cleanup_reaps_successful_owned_child() {
        let (dir, ctx) = fixture("echo $$ > \"$HOME/pid\"; exit 0");
        assert!(run(&ctx).is_empty());
        let pid = std::fs::read_to_string(dir.path().join("pid"))
            .unwrap()
            .trim()
            .parse::<i32>()
            .unwrap();
        assert_eq!(
            unsafe { libc::waitpid(pid, std::ptr::null_mut(), libc::WNOHANG) },
            -1
        );
        assert_eq!(
            std::io::Error::last_os_error().raw_os_error(),
            Some(libc::ECHILD)
        );
    }
    #[test]
    fn cleanup_reports_failed_down_without_repeating_or_fallback() {
        let (dir, ctx) = fixture("[ \"$1\" = ps ] && { echo 012345abcdef; exit 0; }\nexit 2");
        let errors = run(&ctx);
        assert_eq!(errors.len(), 1);
        assert!(
            errors[0].to_string().contains("take down owned"),
            "{errors:?}"
        );
        assert_eq!(calls(&dir).lines().count(), 2);
    }
    #[test]
    fn timed_out_creation_retains_candidate_even_after_control_child_is_reaped() {
        let (dir, ctx) = fixture(
            "if [ \"$1\" = run ]; then echo $$ > \"$HOME/pid\"; exec /bin/sleep 30; fi\nexit 0",
        );
        ctx.cancel.creation_started("ambiguous-create".into());
        let (result, receipts) =
            observed(Some(("run".into(), dir.path().join("pid"), false)), || {
                docker_control(&ctx, &["run", "-d"], Duration::from_millis(100))
            });
        assert!(result.unwrap_err().to_string().contains("deadline"));
        assert_eq!(receipts.len(), 1);
        assert_eq!(
            unsafe { libc::waitpid(receipts[0].pid, std::ptr::null_mut(), libc::WNOHANG) },
            -1
        );
        assert_eq!(
            std::io::Error::last_os_error().raw_os_error(),
            Some(libc::ECHILD)
        );
        let cleanup = ctx.cancel.cleanup_owned(&ctx);
        assert_eq!(cleanup.pending.creation_candidates, ["ambiguous-create"]);
        assert!(!cleanup.pending.no_known_pending());
        assert!(!calls(&dir).lines().any(|line| line.starts_with("rm ")));
    }
}