tambo 0.18.0

Install and prove the whole AI knowledge-tool kit
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
//! Bounded Homebrew steps (aegis-f0ne).
//!
//! Measured on the Mac on 2026-11-27: every `/usr/bin/mdfind` started from a
//! launchd agent hangs. Brew runs one for every stack formula it installs. The
//! formulas have no bottle, so `FormulaInstaller#install` runs the
//! build-from-source checks, which ask Spotlight for Xcode.app when only the
//! Command Line Tools are present. By then `brew upgrade` has already unlinked
//! the previous keg, so the tool vanished from PATH for as long as the hang
//! lasted. The consumer's own deadline then killed everything and left the keg
//! unlinked.
//!
//! Every brew step therefore runs under a bound. On timeout Tambo kills brew's
//! whole descendant tree, found through `ps`, because brew's `mdfind` runs in
//! a process group of its own and survived a group kill as an orphan. Brew
//! itself stays in Tambo's process group, so a supervisor that group-kills
//! Tambo also kills brew. The caller then restores the keg's link and names the
//! member.
//!
//! Two bounds apply. Each step gets at most `TAMBO_BREW_STEP_TIMEOUT_SECS`
//! (240s). All ordinary steps of one Tambo process share
//! `TAMBO_BREW_BUDGET_SECS` (600s), which stays under the Mac consumer's 900s
//! member budget. Link repair after a failure is not charged to that budget.
//! Each repair step gets 30s, so a spent budget still leaves the keg linked.

use std::{
    ffi::OsStr,
    process::{Command, ExitStatus, Stdio},
    time::{Duration, Instant},
};

/// Default bound for one brew step. A normal upgrade of a stack formula takes
/// seconds; the Mac consumer gives the whole member update 900s.
pub const DEFAULT_STEP_TIMEOUT: Duration = Duration::from_secs(240);

/// Default total for all ordinary brew steps of one Tambo process.
pub const DEFAULT_BUDGET: Duration = Duration::from_secs(600);

/// Bound for each link-repair step after a failure.
pub const REPAIR_TIMEOUT: Duration = Duration::from_secs(30);

fn seconds(name: &str, default: Duration) -> Duration {
    std::env::var(name)
        .ok()
        .and_then(|raw| raw.trim().parse::<u64>().ok())
        .filter(|secs| *secs > 0)
        .map_or(default, Duration::from_secs)
}

/// The per-step bound, overridable for tests and slow hosts.
#[must_use]
pub fn step_timeout() -> Duration {
    seconds("TAMBO_BREW_STEP_TIMEOUT_SECS", DEFAULT_STEP_TIMEOUT)
}

/// The shared budget for this process's ordinary brew steps.
fn budget() -> Duration {
    seconds("TAMBO_BREW_BUDGET_SECS", DEFAULT_BUDGET)
}

/// When this process's brew budget ends. The clock starts at the first brew step.
fn budget_end() -> Instant {
    static END: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
    *END.get_or_init(|| Instant::now() + budget())
}

/// Which bound a step runs under.
#[derive(Clone, Copy)]
pub enum Bound {
    /// An ordinary step: the step bound, capped by what is left of the budget.
    Step,
    /// Link repair after a failure: a fixed short bound outside the budget.
    Repair,
}

impl Bound {
    fn timeout(self) -> Duration {
        match self {
            Bound::Step => {
                step_timeout().min(budget_end().saturating_duration_since(Instant::now()))
            }
            Bound::Repair => REPAIR_TIMEOUT,
        }
    }
}

/// A brew step that did not finish within its bound, or never started
/// because the shared budget was already spent.
#[derive(Debug)]
pub struct TimedOut {
    pub elapsed: Duration,
    /// Processes killed, the brew process included.
    pub killed: usize,
    /// The step was not started: the budget had run out (eph-review-07aef5).
    pub budget_spent: bool,
}

impl std::fmt::Display for TimedOut {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.budget_spent {
            // Keeps the `timed out after <N>s ` shape the Mac consumer parses.
            return write!(
                f,
                "timed out after {}s (the shared brew budget TAMBO_BREW_BUDGET_SECS \
                 was spent before this step started; nothing was run)",
                self.elapsed.as_secs()
            );
        }
        write!(
            f,
            "timed out after {}s (killed {} process{})",
            self.elapsed.as_secs(),
            self.killed,
            if self.killed == 1 { "" } else { "es" }
        )
    }
}

impl std::error::Error for TimedOut {}

/// What a bounded step produced.
#[derive(Debug)]
pub struct Finished {
    pub status: ExitStatus,
    pub stdout: Vec<u8>,
}

/// How a bounded step treats its standard output.
#[derive(Clone, Copy)]
pub enum Output {
    /// Passed through to Tambo's own output (install/upgrade progress).
    Inherit,
    /// Captured and returned (JSON reads).
    Capture,
}

/// Run `program args` with `HOMEBREW_NO_AUTO_UPDATE=1` under `bound`.
pub fn run<I, S>(
    program: &OsStr,
    args: I,
    output: Output,
    bound: Bound,
) -> anyhow::Result<Result<Finished, TimedOut>>
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let timeout = bound.timeout();
    if timeout.is_zero() {
        return Ok(Err(TimedOut {
            elapsed: budget(),
            killed: 0,
            budget_spent: true,
        }));
    }
    run_for(program, args, output, timeout)
}

fn run_for<I, S>(
    program: &OsStr,
    args: I,
    output: Output,
    timeout: Duration,
) -> anyhow::Result<Result<Finished, TimedOut>>
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    use std::io::{Read, Seek};
    let mut command = Command::new(program);
    command
        .args(args)
        .env("HOMEBREW_NO_AUTO_UPDATE", "1")
        // Brew stays in Tambo's process group (eph-review-1d484a): a
        // supervisor that group-kills Tambo must take brew with it.
        .stdin(Stdio::null());
    // A file, not a pipe: a full pipe would block brew and look like a hang.
    let mut captured = match output {
        Output::Capture => {
            let file = tempfile::tempfile()?;
            command.stdout(file.try_clone()?);
            Some(file)
        }
        Output::Inherit => None,
    };
    let start = Instant::now();
    let mut child = command.spawn()?;
    // Descendants seen while the step runs, with their groups, so a process
    // whose parent exits before a timeout is still found (eph-review-07aef5).
    let mut known: Vec<Known> = Vec::new();
    let mut polls: u32 = 0;
    loop {
        if let Some(status) = child.try_wait()? {
            let mut stdout = Vec::new();
            if let Some(file) = captured.as_mut() {
                file.rewind()?;
                file.read_to_end(&mut stdout)?;
            }
            return Ok(Ok(Finished { status, stdout }));
        }
        if start.elapsed() >= timeout {
            let killed = kill_tree(child.id(), &known);
            let _ = child.wait();
            return Ok(Err(TimedOut {
                elapsed: start.elapsed(),
                killed,
                budget_spent: false,
            }));
        }
        polls += 1;
        if polls % 10 == 0 {
            remember_descendants(child.id(), &process_table(), &mut known);
        }
        std::thread::sleep(Duration::from_millis(50));
    }
}

/// One process seen as a descendant of a brew step. Pid, group AND start
/// time identify it, so a pid the kernel reuses for an unrelated process
/// never matches (eph-review-fc24ee).
#[derive(Clone, Debug, PartialEq, Eq)]
struct Known {
    pid: u32,
    pgid: u32,
    start: String,
}

impl Known {
    fn of(row: &Row) -> Self {
        Self {
            pid: row.pid,
            pgid: row.pgid,
            start: row.start.clone(),
        }
    }

    fn is(&self, row: &Row) -> bool {
        self.pid == row.pid && self.pgid == row.pgid && self.start == row.start
    }
}

/// Prune exited entries from `known`, then add `root`'s current descendants.
/// An entry stays only while the same process (pid, group and start time)
/// is still in the table.
fn remember_descendants(root: u32, table: &[Row], known: &mut Vec<Known>) {
    known.retain(|entry| table.iter().any(|row| entry.is(row)));
    let mut frontier = children_of(table, root);
    while let Some(pid) = frontier.pop() {
        if let Some(row) = table.iter().find(|row| row.pid == pid) {
            if !known.iter().any(|entry| entry.is(row)) {
                known.push(Known::of(row));
            }
        }
        frontier.extend(children_of(table, pid));
    }
}

/// Earlier descendants that are now reparented to init: the very process
/// seen before (pid, group and start time all still equal), parent 1.
fn reparented(table: &[Row], known: &[Known]) -> Vec<u32> {
    table
        .iter()
        .filter(|row| row.ppid == 1 && known.iter().any(|entry| entry.is(row)))
        .map(|row| row.pid)
        .collect()
}

/// SIGKILL `root` and every descendant, in any process group. Never signals
/// a process group: brew shares Tambo's. Returns how many processes were
/// signalled.
///
/// A descendant whose parent already exited has been reparented to init and
/// is no longer anyone's child (eph-review-07aef5). Two rules still find it:
/// it was seen as a descendant earlier (`known`, matched on pid, group and
/// start time at kill time, so a reused pid is not killed) and now has
/// parent 1, or it shares the
/// process group of a live descendant, other than Tambo's own group.
fn kill_tree(root: u32, known: &[Known]) -> usize {
    // SAFETY: getpgrp only reads this process's group id.
    let ours = u32::try_from(unsafe { libc::getpgrp() }).unwrap_or(0);
    // Freeze the tree first so nothing forks a new child between the listing
    // and the kill. A stopped process cannot fork.
    let mut seen = Vec::new();
    let mut frontier = vec![root];
    loop {
        let table = process_table();
        while let Some(pid) = frontier.pop() {
            if seen.contains(&pid) {
                continue;
            }
            signal(pid, libc::SIGSTOP);
            seen.push(pid);
            frontier.extend(children_of(&table, pid));
        }
        // Earlier descendants, now reparented to init.
        frontier.extend(
            reparented(&table, known)
                .into_iter()
                .filter(|pid| !seen.contains(pid)),
        );
        // Processes in a descendant's own group that are not yet seen.
        let groups: Vec<u32> = table
            .iter()
            .filter(|row| seen.contains(&row.pid) && row.pgid != ours)
            .map(|row| row.pgid)
            .collect();
        frontier.extend(
            table
                .iter()
                .filter(|row| groups.contains(&row.pgid) && !seen.contains(&row.pid))
                .map(|row| row.pid),
        );
        if frontier.is_empty() {
            break;
        }
    }
    for pid in &seen {
        signal(*pid, libc::SIGKILL);
    }
    seen.len()
}

fn signal(pid: u32, sig: libc::c_int) {
    if let Ok(pid) = libc::pid_t::try_from(pid) {
        // SAFETY: kill only sends a signal; a vanished pid is ESRCH.
        unsafe {
            libc::kill(pid, sig);
        }
    }
}

struct Row {
    pid: u32,
    ppid: u32,
    pgid: u32,
    /// `ps` lstart, e.g. `Fri Nov 27 17:05:53 2026`.
    start: String,
}

/// Every process with its parent and group, from `ps` (portable across macOS
/// and Linux; `/proc` is absent on the Mac).
fn process_table() -> Vec<Row> {
    let Ok(out) = Command::new("/bin/ps")
        .args(["-A", "-o", "pid=,ppid=,pgid=,lstart="])
        .output()
    else {
        return Vec::new();
    };
    parse_table(&String::from_utf8_lossy(&out.stdout))
}

fn parse_table(listing: &str) -> Vec<Row> {
    listing
        .lines()
        .filter_map(|line| {
            let mut fields = line.split_whitespace();
            let pid = fields.next()?.parse().ok()?;
            let ppid = fields.next()?.parse().ok()?;
            let pgid = fields.next()?.parse().ok()?;
            let start = fields.collect::<Vec<_>>().join(" ");
            (!start.is_empty()).then_some(Row {
                pid,
                ppid,
                pgid,
                start,
            })
        })
        .collect()
}

fn children_of(table: &[Row], parent: u32) -> Vec<u32> {
    table
        .iter()
        .filter(|row| row.ppid == parent)
        .map(|row| row.pid)
        .collect()
}

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

    #[test]
    fn children_are_read_from_a_ps_listing() {
        let t = "Fri Nov 27 17:05:53 2026";
        let listing = format!(
            "  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"
        );
        let listing = listing.as_str();
        let table = parse_table(listing);
        assert_eq!(children_of(&table, 10), vec![11, 12, 13]);
        assert!(children_of(&table, 99).is_empty());
        assert_eq!(table.iter().find(|r| r.pid == 12).unwrap().pgid, 12);
        assert_eq!(table.iter().find(|r| r.pid == 12).unwrap().start, t);
        // A row without a start time is not trusted.
        assert!(table.iter().all(|r| r.pid != 14));
    }

    #[test]
    fn a_reused_pid_is_never_killed_as_a_known_descendant() {
        // eph-review-fc24ee: pid 50 was brew's descendant in group 50 and
        // exited; the kernel reused 50 for an unrelated process that happens
        // to have parent 1 and group 50. Only the start time tells them apart.
        let row = |pid, ppid, pgid, start: &str| Row {
            pid,
            ppid,
            pgid,
            start: start.into(),
        };
        let seen_then = row(50, 40, 50, "Fri Nov 27 17:00:00 2026");
        let mut known = Vec::new();
        remember_descendants(40, &[row(40, 9, 9, "x"), seen_then], &mut known);
        assert_eq!(known.len(), 1);
        let reused = [row(50, 1, 50, "Fri Nov 27 17:04:00 2026")];
        assert!(reparented(&reused, &known).is_empty());
        // The very process, reparented, is still found.
        let same = [row(50, 1, 50, "Fri Nov 27 17:00:00 2026")];
        assert_eq!(reparented(&same, &known), vec![50]);
        // A sample without it prunes it, so a later reuse cannot match.
        remember_descendants(40, &reused, &mut known);
        assert!(known.is_empty());
    }

    #[test]
    fn a_reparented_descendant_in_a_child_group_is_killed() {
        // eph-review-07aef5: the parent of an own-group process exits first,
        // so the process is reparented to init and is nobody's child.
        let dir = tempfile::tempdir().unwrap();
        let pidfile = dir.path().join("orphan.pid");
        // The middle process starts its own group, forks a sleeper into it,
        // records it and exits after 1s; the outer shell then hangs.
        let script = format!(
            "perl -e 'setpgrp(0,0); my $p = fork(); if ($p == 0) {{ exec \"sleep\", \"300\" }} \
             open(F, \">\", \"{}\"); print F $p; close F; sleep 1; exit 0'; sleep 300",
            pidfile.display()
        );
        let timed_out = run_for(
            OsStr::new("/bin/sh"),
            ["-c", &script],
            Output::Inherit,
            Duration::from_secs(3),
        )
        .unwrap()
        .unwrap_err();
        let orphan: libc::pid_t = std::fs::read_to_string(&pidfile)
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        let mut alive = true;
        for _ in 0..40 {
            // SAFETY: signal 0 only probes for existence.
            alive = unsafe { libc::kill(orphan, 0) } == 0;
            if !alive {
                break;
            }
            std::thread::sleep(Duration::from_millis(50));
        }
        assert!(!alive, "reparented orphan survived: {timed_out}");
    }

    #[test]
    fn a_spent_budget_is_reported_as_such() {
        let text = TimedOut {
            elapsed: Duration::from_secs(600),
            killed: 0,
            budget_spent: true,
        }
        .to_string();
        assert!(text.starts_with("timed out after 600s ("), "{text}");
        assert!(text.contains("budget"), "{text}");
        assert!(!text.contains("killed"), "{text}");
    }

    #[test]
    fn brew_stays_in_tambos_process_group() {
        // eph-review-1d484a: a supervisor that group-kills Tambo must take
        // brew with it, so a step must not start a process group of its own.
        let done = run_for(
            OsStr::new("/bin/sh"),
            ["-c", "ps -o pgid= -p $$"],
            Output::Capture,
            Duration::from_secs(10),
        )
        .unwrap()
        .unwrap();
        // SAFETY: getpgrp only reads this process's group id.
        let ours = unsafe { libc::getpgrp() };
        assert_eq!(
            String::from_utf8_lossy(&done.stdout).trim(),
            ours.to_string()
        );
    }

    #[test]
    fn a_finished_step_returns_its_captured_output() {
        let done = run_for(
            OsStr::new("/bin/sh"),
            ["-c", "echo hello; exit 3"],
            Output::Capture,
            Duration::from_secs(10),
        )
        .unwrap()
        .unwrap();
        assert_eq!(done.status.code(), Some(3));
        assert_eq!(done.stdout, b"hello\n");
    }

    #[test]
    fn a_hung_step_and_a_child_in_its_own_group_are_both_killed() {
        // The mdfind shape: a grandchild that leaves brew's process group.
        let dir = tempfile::tempdir().unwrap();
        let pidfile = dir.path().join("orphan.pid");
        let script = format!(
            "perl -e 'setpgrp(0,0); exec \"sleep\", \"300\"' & echo $! > {}; wait",
            pidfile.display()
        );
        let timed_out = run_for(
            OsStr::new("/bin/sh"),
            ["-c", &script],
            Output::Inherit,
            Duration::from_millis(800),
        )
        .unwrap()
        .unwrap_err();
        assert!(timed_out.killed >= 2, "{timed_out}");
        let orphan: libc::pid_t = std::fs::read_to_string(&pidfile)
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        let mut alive = true;
        for _ in 0..40 {
            // SAFETY: signal 0 only probes for existence.
            alive = unsafe { libc::kill(orphan, 0) } == 0;
            if !alive {
                break;
            }
            std::thread::sleep(Duration::from_millis(50));
        }
        assert!(!alive, "the own-group grandchild survived the timeout");
        let text = timed_out.to_string();
        assert!(
            text.starts_with("timed out after ") && text.contains("s (killed "),
            "{text}"
        );
    }
}