Skip to main content

caboodle/
brew_bound.rs

1//! Bounded Homebrew steps (aegis-f0ne).
2//!
3//! Measured on the Mac on 2026-11-27: every `/usr/bin/mdfind` started from a
4//! launchd agent hangs. Brew runs one for every stack formula it installs. The
5//! formulas have no bottle, so `FormulaInstaller#install` runs the
6//! build-from-source checks, which ask Spotlight for Xcode.app when only the
7//! Command Line Tools are present. By then `brew upgrade` has already unlinked
8//! the previous keg, so the tool vanished from PATH for as long as the hang
9//! lasted. The consumer's own deadline then killed everything and left the keg
10//! unlinked.
11//!
12//! Every brew step therefore runs under a bound. On timeout Tambo kills brew's
13//! whole descendant tree, found through `ps`, because brew's `mdfind` runs in
14//! a process group of its own and survived a group kill as an orphan. Brew
15//! itself stays in Tambo's process group, so a supervisor that group-kills
16//! Tambo also kills brew. The caller then restores the keg's link and names the
17//! member.
18//!
19//! Two bounds apply. Each step gets at most `TAMBO_BREW_STEP_TIMEOUT_SECS`
20//! (240s). All ordinary steps of one Tambo process share
21//! `TAMBO_BREW_BUDGET_SECS` (600s), which stays under the Mac consumer's 900s
22//! member budget. Link repair after a failure is not charged to that budget.
23//! Each repair step gets 30s, so a spent budget still leaves the keg linked.
24
25use std::{
26    ffi::OsStr,
27    process::{Command, ExitStatus, Stdio},
28    time::{Duration, Instant},
29};
30
31/// Default bound for one brew step. A normal upgrade of a stack formula takes
32/// seconds; the Mac consumer gives the whole member update 900s.
33pub const DEFAULT_STEP_TIMEOUT: Duration = Duration::from_secs(240);
34
35/// Default total for all ordinary brew steps of one Tambo process.
36pub const DEFAULT_BUDGET: Duration = Duration::from_secs(600);
37
38/// Bound for each link-repair step after a failure.
39pub const REPAIR_TIMEOUT: Duration = Duration::from_secs(30);
40
41fn seconds(name: &str, default: Duration) -> Duration {
42    std::env::var(name)
43        .ok()
44        .and_then(|raw| raw.trim().parse::<u64>().ok())
45        .filter(|secs| *secs > 0)
46        .map_or(default, Duration::from_secs)
47}
48
49/// The per-step bound, overridable for tests and slow hosts.
50#[must_use]
51pub fn step_timeout() -> Duration {
52    seconds("TAMBO_BREW_STEP_TIMEOUT_SECS", DEFAULT_STEP_TIMEOUT)
53}
54
55/// The shared budget for this process's ordinary brew steps.
56fn budget() -> Duration {
57    seconds("TAMBO_BREW_BUDGET_SECS", DEFAULT_BUDGET)
58}
59
60/// When this process's brew budget ends. The clock starts at the first brew step.
61fn budget_end() -> Instant {
62    static END: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
63    *END.get_or_init(|| Instant::now() + budget())
64}
65
66/// Which bound a step runs under.
67#[derive(Clone, Copy)]
68pub enum Bound {
69    /// An ordinary step: the step bound, capped by what is left of the budget.
70    Step,
71    /// Link repair after a failure: a fixed short bound outside the budget.
72    Repair,
73}
74
75impl Bound {
76    fn timeout(self) -> Duration {
77        match self {
78            Bound::Step => {
79                step_timeout().min(budget_end().saturating_duration_since(Instant::now()))
80            }
81            Bound::Repair => REPAIR_TIMEOUT,
82        }
83    }
84}
85
86/// A brew step that did not finish within its bound, or never started
87/// because the shared budget was already spent.
88#[derive(Debug)]
89pub struct TimedOut {
90    pub elapsed: Duration,
91    /// Processes killed, the brew process included.
92    pub killed: usize,
93    /// The step was not started: the budget had run out (eph-review-07aef5).
94    pub budget_spent: bool,
95}
96
97impl std::fmt::Display for TimedOut {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        if self.budget_spent {
100            // Keeps the `timed out after <N>s ` shape the Mac consumer parses.
101            return write!(
102                f,
103                "timed out after {}s (the shared brew budget TAMBO_BREW_BUDGET_SECS \
104                 was spent before this step started; nothing was run)",
105                self.elapsed.as_secs()
106            );
107        }
108        write!(
109            f,
110            "timed out after {}s (killed {} process{})",
111            self.elapsed.as_secs(),
112            self.killed,
113            if self.killed == 1 { "" } else { "es" }
114        )
115    }
116}
117
118impl std::error::Error for TimedOut {}
119
120/// What a bounded step produced.
121#[derive(Debug)]
122pub struct Finished {
123    pub status: ExitStatus,
124    pub stdout: Vec<u8>,
125}
126
127/// How a bounded step treats its standard output.
128#[derive(Clone, Copy)]
129pub enum Output {
130    /// Passed through to Tambo's own output (install/upgrade progress).
131    Inherit,
132    /// Captured and returned (JSON reads).
133    Capture,
134}
135
136/// Run `program args` with `HOMEBREW_NO_AUTO_UPDATE=1` under `bound`.
137pub fn run<I, S>(
138    program: &OsStr,
139    args: I,
140    output: Output,
141    bound: Bound,
142) -> anyhow::Result<Result<Finished, TimedOut>>
143where
144    I: IntoIterator<Item = S>,
145    S: AsRef<OsStr>,
146{
147    let timeout = bound.timeout();
148    if timeout.is_zero() {
149        return Ok(Err(TimedOut {
150            elapsed: budget(),
151            killed: 0,
152            budget_spent: true,
153        }));
154    }
155    run_for(program, args, output, timeout)
156}
157
158fn run_for<I, S>(
159    program: &OsStr,
160    args: I,
161    output: Output,
162    timeout: Duration,
163) -> anyhow::Result<Result<Finished, TimedOut>>
164where
165    I: IntoIterator<Item = S>,
166    S: AsRef<OsStr>,
167{
168    use std::io::{Read, Seek};
169    let mut command = Command::new(program);
170    command
171        .args(args)
172        .env("HOMEBREW_NO_AUTO_UPDATE", "1")
173        // Brew stays in Tambo's process group (eph-review-1d484a): a
174        // supervisor that group-kills Tambo must take brew with it.
175        .stdin(Stdio::null());
176    // A file, not a pipe: a full pipe would block brew and look like a hang.
177    let mut captured = match output {
178        Output::Capture => {
179            let file = tempfile::tempfile()?;
180            command.stdout(file.try_clone()?);
181            Some(file)
182        }
183        Output::Inherit => None,
184    };
185    let start = Instant::now();
186    let mut child = command.spawn()?;
187    // Descendants seen while the step runs, with their groups, so a process
188    // whose parent exits before a timeout is still found (eph-review-07aef5).
189    let mut known: Vec<Known> = Vec::new();
190    let mut polls: u32 = 0;
191    loop {
192        if let Some(status) = child.try_wait()? {
193            let mut stdout = Vec::new();
194            if let Some(file) = captured.as_mut() {
195                file.rewind()?;
196                file.read_to_end(&mut stdout)?;
197            }
198            return Ok(Ok(Finished { status, stdout }));
199        }
200        if start.elapsed() >= timeout {
201            let killed = kill_tree(child.id(), &known);
202            let _ = child.wait();
203            return Ok(Err(TimedOut {
204                elapsed: start.elapsed(),
205                killed,
206                budget_spent: false,
207            }));
208        }
209        polls += 1;
210        if polls % 10 == 0 {
211            remember_descendants(child.id(), &process_table(), &mut known);
212        }
213        std::thread::sleep(Duration::from_millis(50));
214    }
215}
216
217/// One process seen as a descendant of a brew step. Pid, group AND start
218/// time identify it, so a pid the kernel reuses for an unrelated process
219/// never matches (eph-review-fc24ee).
220#[derive(Clone, Debug, PartialEq, Eq)]
221struct Known {
222    pid: u32,
223    pgid: u32,
224    start: String,
225}
226
227impl Known {
228    fn of(row: &Row) -> Self {
229        Self {
230            pid: row.pid,
231            pgid: row.pgid,
232            start: row.start.clone(),
233        }
234    }
235
236    fn is(&self, row: &Row) -> bool {
237        self.pid == row.pid && self.pgid == row.pgid && self.start == row.start
238    }
239}
240
241/// Prune exited entries from `known`, then add `root`'s current descendants.
242/// An entry stays only while the same process (pid, group and start time)
243/// is still in the table.
244fn remember_descendants(root: u32, table: &[Row], known: &mut Vec<Known>) {
245    known.retain(|entry| table.iter().any(|row| entry.is(row)));
246    let mut frontier = children_of(table, root);
247    while let Some(pid) = frontier.pop() {
248        if let Some(row) = table.iter().find(|row| row.pid == pid) {
249            if !known.iter().any(|entry| entry.is(row)) {
250                known.push(Known::of(row));
251            }
252        }
253        frontier.extend(children_of(table, pid));
254    }
255}
256
257/// Earlier descendants that are now reparented to init: the very process
258/// seen before (pid, group and start time all still equal), parent 1.
259fn reparented(table: &[Row], known: &[Known]) -> Vec<u32> {
260    table
261        .iter()
262        .filter(|row| row.ppid == 1 && known.iter().any(|entry| entry.is(row)))
263        .map(|row| row.pid)
264        .collect()
265}
266
267/// SIGKILL `root` and every descendant, in any process group. Never signals
268/// a process group: brew shares Tambo's. Returns how many processes were
269/// signalled.
270///
271/// A descendant whose parent already exited has been reparented to init and
272/// is no longer anyone's child (eph-review-07aef5). Two rules still find it:
273/// it was seen as a descendant earlier (`known`, matched on pid, group and
274/// start time at kill time, so a reused pid is not killed) and now has
275/// parent 1, or it shares the
276/// process group of a live descendant, other than Tambo's own group.
277fn kill_tree(root: u32, known: &[Known]) -> usize {
278    // SAFETY: getpgrp only reads this process's group id.
279    let ours = u32::try_from(unsafe { libc::getpgrp() }).unwrap_or(0);
280    // Freeze the tree first so nothing forks a new child between the listing
281    // and the kill. A stopped process cannot fork.
282    let mut seen = Vec::new();
283    let mut frontier = vec![root];
284    loop {
285        let table = process_table();
286        while let Some(pid) = frontier.pop() {
287            if seen.contains(&pid) {
288                continue;
289            }
290            signal(pid, libc::SIGSTOP);
291            seen.push(pid);
292            frontier.extend(children_of(&table, pid));
293        }
294        // Earlier descendants, now reparented to init.
295        frontier.extend(
296            reparented(&table, known)
297                .into_iter()
298                .filter(|pid| !seen.contains(pid)),
299        );
300        // Processes in a descendant's own group that are not yet seen.
301        let groups: Vec<u32> = table
302            .iter()
303            .filter(|row| seen.contains(&row.pid) && row.pgid != ours)
304            .map(|row| row.pgid)
305            .collect();
306        frontier.extend(
307            table
308                .iter()
309                .filter(|row| groups.contains(&row.pgid) && !seen.contains(&row.pid))
310                .map(|row| row.pid),
311        );
312        if frontier.is_empty() {
313            break;
314        }
315    }
316    for pid in &seen {
317        signal(*pid, libc::SIGKILL);
318    }
319    seen.len()
320}
321
322fn signal(pid: u32, sig: libc::c_int) {
323    if let Ok(pid) = libc::pid_t::try_from(pid) {
324        // SAFETY: kill only sends a signal; a vanished pid is ESRCH.
325        unsafe {
326            libc::kill(pid, sig);
327        }
328    }
329}
330
331struct Row {
332    pid: u32,
333    ppid: u32,
334    pgid: u32,
335    /// `ps` lstart, e.g. `Fri Nov 27 17:05:53 2026`.
336    start: String,
337}
338
339/// Every process with its parent and group, from `ps` (portable across macOS
340/// and Linux; `/proc` is absent on the Mac).
341fn process_table() -> Vec<Row> {
342    let Ok(out) = Command::new("/bin/ps")
343        .args(["-A", "-o", "pid=,ppid=,pgid=,lstart="])
344        .output()
345    else {
346        return Vec::new();
347    };
348    parse_table(&String::from_utf8_lossy(&out.stdout))
349}
350
351fn parse_table(listing: &str) -> Vec<Row> {
352    listing
353        .lines()
354        .filter_map(|line| {
355            let mut fields = line.split_whitespace();
356            let pid = fields.next()?.parse().ok()?;
357            let ppid = fields.next()?.parse().ok()?;
358            let pgid = fields.next()?.parse().ok()?;
359            let start = fields.collect::<Vec<_>>().join(" ");
360            (!start.is_empty()).then_some(Row {
361                pid,
362                ppid,
363                pgid,
364                start,
365            })
366        })
367        .collect()
368}
369
370fn children_of(table: &[Row], parent: u32) -> Vec<u32> {
371    table
372        .iter()
373        .filter(|row| row.ppid == parent)
374        .map(|row| row.pid)
375        .collect()
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381
382    #[test]
383    fn children_are_read_from_a_ps_listing() {
384        let t = "Fri Nov 27 17:05:53 2026";
385        let listing = format!(
386            "  1     0  1 {t}\n 10     1 10 {t}\n 11    10 10 {t}\n 12    10 12 {t}\n garbage\n 13 10 10 {t}\n 14 10 10\n"
387        );
388        let listing = listing.as_str();
389        let table = parse_table(listing);
390        assert_eq!(children_of(&table, 10), vec![11, 12, 13]);
391        assert!(children_of(&table, 99).is_empty());
392        assert_eq!(table.iter().find(|r| r.pid == 12).unwrap().pgid, 12);
393        assert_eq!(table.iter().find(|r| r.pid == 12).unwrap().start, t);
394        // A row without a start time is not trusted.
395        assert!(table.iter().all(|r| r.pid != 14));
396    }
397
398    #[test]
399    fn a_reused_pid_is_never_killed_as_a_known_descendant() {
400        // eph-review-fc24ee: pid 50 was brew's descendant in group 50 and
401        // exited; the kernel reused 50 for an unrelated process that happens
402        // to have parent 1 and group 50. Only the start time tells them apart.
403        let row = |pid, ppid, pgid, start: &str| Row {
404            pid,
405            ppid,
406            pgid,
407            start: start.into(),
408        };
409        let seen_then = row(50, 40, 50, "Fri Nov 27 17:00:00 2026");
410        let mut known = Vec::new();
411        remember_descendants(40, &[row(40, 9, 9, "x"), seen_then], &mut known);
412        assert_eq!(known.len(), 1);
413        let reused = [row(50, 1, 50, "Fri Nov 27 17:04:00 2026")];
414        assert!(reparented(&reused, &known).is_empty());
415        // The very process, reparented, is still found.
416        let same = [row(50, 1, 50, "Fri Nov 27 17:00:00 2026")];
417        assert_eq!(reparented(&same, &known), vec![50]);
418        // A sample without it prunes it, so a later reuse cannot match.
419        remember_descendants(40, &reused, &mut known);
420        assert!(known.is_empty());
421    }
422
423    #[test]
424    fn a_reparented_descendant_in_a_child_group_is_killed() {
425        // eph-review-07aef5: the parent of an own-group process exits first,
426        // so the process is reparented to init and is nobody's child.
427        let dir = tempfile::tempdir().unwrap();
428        let pidfile = dir.path().join("orphan.pid");
429        // The middle process starts its own group, forks a sleeper into it,
430        // records it and exits after 1s; the outer shell then hangs.
431        let script = format!(
432            "perl -e 'setpgrp(0,0); my $p = fork(); if ($p == 0) {{ exec \"sleep\", \"300\" }} \
433             open(F, \">\", \"{}\"); print F $p; close F; sleep 1; exit 0'; sleep 300",
434            pidfile.display()
435        );
436        let timed_out = run_for(
437            OsStr::new("/bin/sh"),
438            ["-c", &script],
439            Output::Inherit,
440            Duration::from_secs(3),
441        )
442        .unwrap()
443        .unwrap_err();
444        let orphan: libc::pid_t = std::fs::read_to_string(&pidfile)
445            .unwrap()
446            .trim()
447            .parse()
448            .unwrap();
449        let mut alive = true;
450        for _ in 0..40 {
451            // SAFETY: signal 0 only probes for existence.
452            alive = unsafe { libc::kill(orphan, 0) } == 0;
453            if !alive {
454                break;
455            }
456            std::thread::sleep(Duration::from_millis(50));
457        }
458        assert!(!alive, "reparented orphan survived: {timed_out}");
459    }
460
461    #[test]
462    fn a_spent_budget_is_reported_as_such() {
463        let text = TimedOut {
464            elapsed: Duration::from_secs(600),
465            killed: 0,
466            budget_spent: true,
467        }
468        .to_string();
469        assert!(text.starts_with("timed out after 600s ("), "{text}");
470        assert!(text.contains("budget"), "{text}");
471        assert!(!text.contains("killed"), "{text}");
472    }
473
474    #[test]
475    fn brew_stays_in_tambos_process_group() {
476        // eph-review-1d484a: a supervisor that group-kills Tambo must take
477        // brew with it, so a step must not start a process group of its own.
478        let done = run_for(
479            OsStr::new("/bin/sh"),
480            ["-c", "ps -o pgid= -p $$"],
481            Output::Capture,
482            Duration::from_secs(10),
483        )
484        .unwrap()
485        .unwrap();
486        // SAFETY: getpgrp only reads this process's group id.
487        let ours = unsafe { libc::getpgrp() };
488        assert_eq!(
489            String::from_utf8_lossy(&done.stdout).trim(),
490            ours.to_string()
491        );
492    }
493
494    #[test]
495    fn a_finished_step_returns_its_captured_output() {
496        let done = run_for(
497            OsStr::new("/bin/sh"),
498            ["-c", "echo hello; exit 3"],
499            Output::Capture,
500            Duration::from_secs(10),
501        )
502        .unwrap()
503        .unwrap();
504        assert_eq!(done.status.code(), Some(3));
505        assert_eq!(done.stdout, b"hello\n");
506    }
507
508    #[test]
509    fn a_hung_step_and_a_child_in_its_own_group_are_both_killed() {
510        // The mdfind shape: a grandchild that leaves brew's process group.
511        let dir = tempfile::tempdir().unwrap();
512        let pidfile = dir.path().join("orphan.pid");
513        let script = format!(
514            "perl -e 'setpgrp(0,0); exec \"sleep\", \"300\"' & echo $! > {}; wait",
515            pidfile.display()
516        );
517        let timed_out = run_for(
518            OsStr::new("/bin/sh"),
519            ["-c", &script],
520            Output::Inherit,
521            Duration::from_millis(800),
522        )
523        .unwrap()
524        .unwrap_err();
525        assert!(timed_out.killed >= 2, "{timed_out}");
526        let orphan: libc::pid_t = std::fs::read_to_string(&pidfile)
527            .unwrap()
528            .trim()
529            .parse()
530            .unwrap();
531        let mut alive = true;
532        for _ in 0..40 {
533            // SAFETY: signal 0 only probes for existence.
534            alive = unsafe { libc::kill(orphan, 0) } == 0;
535            if !alive {
536                break;
537            }
538            std::thread::sleep(Duration::from_millis(50));
539        }
540        assert!(!alive, "the own-group grandchild survived the timeout");
541        let text = timed_out.to_string();
542        assert!(
543            text.starts_with("timed out after ") && text.contains("s (killed "),
544            "{text}"
545        );
546    }
547}