garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/stall.rs

raw

//! A command on a node that does nothing must not hold its session for ever.
//!
//! s857's `cargo clippy …; cargo xtask app Calculator 2>&1 | grep … | head`
//! on mac-2 (2026-11-27 15:33 UTC) never ended: the xtask failed early and
//! left the QEMU it had started behind, orphaned to launchd, with its stderr
//! still the pipe into `grep`. `grep` waited for an end of input that never
//! came, the shell waited for `grep`, and the ssh session stayed open for 20
//! hours — which also kept the lease alive (an open session is use) and kept
//! the agent waiting for a command that would never tell it anything. Nothing
//! ran: the two QEMUs used 0.3 s of CPU a minute between them.
//!
//! So `midas node session` runs an agent's command under this watch:
//!
//! * **Its own process group**, which everything it starts stays in unless it
//!   leaves on purpose (`setsid`) — the orphaned QEMUs were still in it. The
//!   group is what is measured and what is stopped.
//! * **Its output through midas**, not straight into sshd's pipes. Output is
//!   progress, and a process left behind holding the command's output can
//!   no longer keep the session open after the command itself has ended
//!   ([`LINGER`]): `ssh node 'server &'` used to hang the same way.
//! * **Quiet** is no output and less than [`PROGRESS_CPU_MS`] of CPU a minute
//!   for the group. Quiet for [`WARN`] is said on the command's stderr; for
//!   [`STOP`] the group is stopped (SIGTERM, SIGKILL [`GRACE`] later), unless
//!   another command on the node is moving — a cargo waiting for the build
//!   directory's lock is quiet while the build it waits for is not.
//! * Stopping it ends the ssh, and an agent's background command ending is
//!   what wakes an idle Claude Code session; the stop's own lines say why.
//!
//! `MIDAS_STALL=off` (or a duration: `90s`, `45m`, `2h`) as the command's first
//! word sets it for one command, as an environment variable would.

use std::io::{Read, Write};
use std::os::fd::FromRawFd;
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{mpsc, Arc};
use std::time::{Duration, Instant};

/// Quiet this long: said on the command's stderr, and to the hub's log.
pub const WARN: Duration = Duration::from_secs(15 * 60);
/// Quiet this long: stopped. Half an hour of no output and no CPU is not a
/// build: a cold cartopolis build prints a line every few seconds and keeps
/// every core busy.
pub const STOP: Duration = Duration::from_secs(30 * 60);
/// CPU a quiet group may still use in a minute: a little over 1.5 % of one
/// core. The two idle QEMUs used 0.34 s a minute; a build uses minutes.
pub const PROGRESS_CPU_MS: u64 = 1000;
/// How long a command's output may stay open after the command ended, for a
/// last write to arrive, before the session ends without it.
pub const LINGER: Duration = Duration::from_secs(2);
/// Between SIGTERM and SIGKILL.
pub const GRACE: Duration = Duration::from_secs(10);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limits {
    pub warn: Duration,
    pub stop: Duration,
}

impl Limits {
    pub const DEFAULT: Limits = Limits { warn: WARN, stop: STOP };

    /// How often the group's CPU is read: once a minute, or a tenth of the
    /// stop for a short one (a test, a `MIDAS_STALL=60s`).
    fn sample(&self) -> Duration {
        (self.stop / 10).clamp(Duration::from_millis(200), Duration::from_secs(60))
    }
}

/// The limits for `command`: the default, another set by a leading
/// `MIDAS_STALL=<duration>`, or none for `MIDAS_STALL=off`.
pub fn limits_for(command: &str) -> Option<Limits> {
    let first = command.split_whitespace().next().unwrap_or("");
    let Some(v) = first.strip_prefix("MIDAS_STALL=") else { return Some(Limits::DEFAULT) };
    let v = v.trim_matches(['"', '\'', ';']);
    if matches!(v, "off" | "0" | "no" | "never") {
        return None;
    }
    match crate::util::seconds(v).filter(|s| *s > 0) {
        Some(s) => {
            let stop = Duration::from_secs(s);
            Some(Limits { warn: (stop / 2).min(WARN), stop })
        }
        None => Some(Limits::DEFAULT),
    }
}

/// What a stop says to the agent, on the command's stderr and in the hub's
/// note (`note_stop`): what ran, what was still in its group — the clue, as
/// s857's two QEMUs were — and that finding the cause is its own work. "Run it
/// again with it fixed" alone left the next step to the person, who said the
/// agent must solve it by itself (2026-11-28).
pub fn stopped_words(command: &str, node: &str, quiet: &str, group: &[String]) -> String {
    let left = if group.is_empty() { String::new() } else { format!(" Still in its process group then: {}.", group.join("; ")) };
    format!(
        "midas: stopped `{command}` on {node}: it printed nothing and used no CPU for {quiet}, so it was waiting for \
         something that would never come.{left} This is yours to solve now, without asking the person: find what it \
         waited for (most often a process it started that kept its output open — a QEMU, a server, a pipe into grep — \
         or a lock or a prompt; `ps`, `lsof` and its log on {node} show which), fix that cause, and run it again."
    )
}

/// The hub's note to the session of a node's `stalled` stop event.
pub fn note_stop(ev: &serde_json::Value) -> String {
    let group: Vec<String> = ev["group"].as_array().into_iter().flatten()
        .filter_map(|g| g.as_str().map(str::to_string)).collect();
    let quiet = ev["quiet_s"].as_u64().map_or("half an hour".into(), |s| format!("{} minutes", s / 60));
    stopped_words(&ev["command"].as_str().unwrap_or("").chars().take(120).collect::<String>(),
                  ev["node"].as_str().unwrap_or("its node"), &quiet, &group)
}

/// What the watch has to say, as it happens.
#[derive(Debug, PartialEq, Eq)]
pub enum Said {
    /// Quiet for this long; stopped at the stop limit.
    Quiet(Duration),
    /// Quiet for this long: being stopped now, with what is in its group
    /// (pid and command).
    Stopping(Duration, Vec<String>),
    /// The command ended, and these (pid and command) still hold its output.
    Leftovers(Vec<String>),
}

/// Run `cmd` under the watch and return how it ended. `mark` is touched at
/// every sign of progress (the node's marker of a running command, whose age
/// the heartbeat reports); `others_moving` says whether another command on the
/// node made progress lately, which holds a stop back.
pub fn run(
    mut cmd: Command,
    limits: Limits,
    mark: Option<&Path>,
    others_moving: impl Fn() -> bool,
    mut say: impl FnMut(Said),
) -> std::io::Result<ExitStatus> {
    cmd.process_group(0).stdout(Stdio::piped()).stderr(Stdio::piped());
    let mut child = cmd.spawn()?;
    let pgid = child.id();
    let started = Instant::now();
    // Milliseconds since `started` of the last output, and whether there was any since the last look.
    let out_at = Arc::new(AtomicU64::new(0));
    let fresh = Arc::new(AtomicBool::new(false));
    let (eof_tx, eof_rx) = mpsc::channel::<()>();
    for (src, fd) in [(child.stdout.take().map(|s| Box::new(s) as Box<dyn Read + Send>), 1),
                      (child.stderr.take().map(|s| Box::new(s) as Box<dyn Read + Send>), 2)] {
        let Some(mut src) = src else { continue };
        let (out_at, fresh, eof) = (out_at.clone(), fresh.clone(), eof_tx.clone());
        std::thread::spawn(move || {
            // Written to the session's own descriptor unbuffered: what the
            // command printed reaches the agent as it was printed.
            // SAFETY: a duplicate of this process's fd 1 or 2, owned by the File.
            let mut dst = unsafe { std::fs::File::from_raw_fd(libc::dup(fd)) };
            let mut buf = vec![0u8; 64 * 1024];
            loop {
                match src.read(&mut buf) {
                    Ok(0) => break,
                    Ok(n) => {
                        out_at.store(started.elapsed().as_millis() as u64, Ordering::Relaxed);
                        fresh.store(true, Ordering::Relaxed);
                        if dst.write_all(&buf[..n]).is_err() {
                            // Nobody reads any more (the ssh went); keep draining, so the command is not stopped by a full pipe.
                            continue;
                        }
                    }
                    Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                    Err(_) => break,
                }
            }
            let _ = eof.send(());
        });
    }
    drop(eof_tx);

    let sample = limits.sample();
    let me = std::process::id();
    let mut cpu = crate::procs::group_cpu_ms(&crate::procs::all(), pgid, me);
    let mut moved = Instant::now();
    let mut looked = Instant::now();
    let mut warned = false;
    let mut stopping: Option<Instant> = None;
    let status = loop {
        if let Some(s) = child.try_wait()? {
            break s;
        }
        std::thread::sleep(Duration::from_millis(100).min(sample));
        if looked.elapsed() < sample {
            continue;
        }
        let span = looked.elapsed();
        looked = Instant::now();
        let now_cpu = crate::procs::group_cpu_ms(&crate::procs::all(), pgid, me);
        let used = now_cpu.saturating_sub(cpu);
        cpu = now_cpu;
        // CPU per minute, scaled from however long this look was.
        let per_minute = used as u128 * 60_000 / span.as_millis().max(1);
        if fresh.swap(false, Ordering::Relaxed) || per_minute >= PROGRESS_CPU_MS as u128 {
            moved = Instant::now();
            warned = false;
            if let Some(m) = mark {
                let _ = std::fs::File::options().append(true).open(m).and_then(|f| f.set_modified(std::time::SystemTime::now()));
            }
            continue;
        }
        let quiet = moved.elapsed();
        match stopping {
            Some(at) if at.elapsed() >= GRACE => {
                // SAFETY: kill(2) on our own child's process group.
                unsafe { libc::kill(-(pgid as i32), libc::SIGKILL) };
            }
            Some(_) => {}
            None if quiet >= limits.stop && !others_moving() => {
                say(Said::Stopping(quiet, group(pgid, me)));
                // SAFETY: as above, with SIGTERM.
                unsafe { libc::kill(-(pgid as i32), libc::SIGTERM) };
                stopping = Some(Instant::now());
            }
            None if quiet >= limits.warn && !warned => {
                warned = true;
                say(Said::Quiet(quiet));
            }
            None => {}
        }
    };
    // The command has ended; what it left in its group may still hold its
    // output. A moment for a last line, then the session ends without them.
    let deadline = Instant::now() + LINGER;
    let mut open = 2;
    while open > 0 {
        let left = deadline.saturating_duration_since(Instant::now());
        if left.is_zero() || eof_rx.recv_timeout(left).is_err() {
            break;
        }
        open -= 1;
    }
    if open > 0 {
        say(Said::Leftovers(group(pgid, me)));
    }
    let _ = std::io::stdout().flush();
    Ok(status)
}

/// What is in process group `pgid` but the watcher: pid and command.
fn group(pgid: u32, me: u32) -> Vec<String> {
    crate::procs::all().into_iter().filter(|p| p.pgid == pgid && p.pid != me)
        .map(|p| format!("{} {}", p.pid, p.cmd.chars().take(60).collect::<String>())).collect()
}

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

    fn sh(c: &str) -> Command {
        let mut cmd = Command::new("/bin/sh");
        cmd.arg("-c").arg(c);
        cmd
    }

    #[test]
    fn the_first_word_sets_the_limits() {
        assert_eq!(limits_for("cargo test"), Some(Limits::DEFAULT));
        assert_eq!(limits_for("MIDAS_STALL=off cargo run"), None);
        assert_eq!(limits_for("MIDAS_STALL=2h cargo run"), Some(Limits { warn: WARN, stop: Duration::from_secs(7200) }));
        assert_eq!(limits_for("MIDAS_STALL=60s x"), Some(Limits { warn: Duration::from_secs(30), stop: Duration::from_secs(60) }));
        assert_eq!(limits_for("MIDAS_STALL=soon x"), Some(Limits::DEFAULT));
    }

    /// The stop names the clue and leaves the cause to the agent, not the person.
    #[test]
    fn a_stop_tells_the_agent_to_solve_it_itself() {
        let ev = serde_json::json!({"kind": "stalled", "stage": "stop", "node": "mac-2", "quiet_s": 1830,
                                    "command": "cargo xtask app Calculator 2>&1 | grep x",
                                    "group": ["37664 qemu-system-aarch64 -M virt"]});
        let w = note_stop(&ev);
        assert!(w.contains("`cargo xtask app Calculator 2>&1 | grep x` on mac-2"), "{w}");
        assert!(w.contains("30 minutes") && w.contains("37664 qemu-system-aarch64"), "{w}");
        assert!(w.contains("without asking the person") && w.contains("run it again"), "{w}");
        assert!(crate::collab::wakes("hub", "stalled") && !crate::collab::wakes("hub", "overlap"));
    }

    /// s857's hang, in small: a process orphaned out of a subshell keeps the
    /// pipe into `grep` open, so the pipeline never ends by itself. Under the
    /// watch it is stopped once quiet, and the run returns.
    #[test]
    fn a_pipeline_held_open_by_an_orphan_is_stopped_when_quiet() {
        let limits = Limits { warn: Duration::from_millis(600), stop: Duration::from_millis(1500) };
        let mut said = Vec::new();
        let t = Instant::now();
        let status = run(sh("{ (sleep 600 &) ; echo started; } 2>&1 | grep -E 'never' | head -5; echo DONE"),
                         limits, None, || false, |s| said.push(s)).unwrap();
        assert!(t.elapsed() < Duration::from_secs(20), "took {:?}", t.elapsed());
        assert!(!status.success());
        assert!(matches!(said.first(), Some(Said::Quiet(_))), "{said:?}");
        assert!(said.iter().any(|s| matches!(s, Said::Stopping(..))), "{said:?}");
    }

    /// The other shape: the command ends, but what it started in the
    /// background holds its output. The session ends anyway, and says so.
    #[test]
    fn a_command_that_ended_is_not_held_open_by_what_it_left() {
        let mut said = Vec::new();
        let t = Instant::now();
        let status = run(sh("sleep 600 & echo started"), Limits::DEFAULT, None, || false, |s| said.push(s)).unwrap();
        assert!(status.success());
        assert!(t.elapsed() < LINGER + Duration::from_secs(3), "took {:?}", t.elapsed());
        let Some(Said::Leftovers(held)) = said.last() else { panic!("{said:?}") };
        assert!(held.iter().any(|h| h.contains("sleep 600")), "{held:?}");
        // Left as it is: stopping what a command started on purpose is not the watch's business.
        for h in held {
            let pid: i32 = h.split_whitespace().next().unwrap().parse().unwrap();
            unsafe { libc::kill(pid, libc::SIGTERM) };
        }
    }

    /// Busy is not quiet, and another command moving holds a stop back.
    #[test]
    fn work_and_other_work_are_not_stalls() {
        let limits = Limits { warn: Duration::from_millis(400), stop: Duration::from_millis(800) };
        let mut said = Vec::new();
        let busy = run(sh("i=0; while [ $i -lt 400000 ]; do i=$((i+1)); done"), limits, None, || false, |s| said.push(s)).unwrap();
        assert!(busy.success());
        let held = run(sh("sleep 3"), limits, None, || true, |s| said.push(s)).unwrap();
        assert!(held.success(), "stopped although another command moved");
        assert!(!said.iter().any(|s| matches!(s, Said::Stopping(..))), "{said:?}");
    }
}