git clone https://garage44.eu/jeroen/midas.gitcartopolis-agent · 2026-11-28T12:09:48Z
feat(node): a command that does nothing no longer holds its ssh for ever s857's `cargo clippy …; cargo xtask app Calculator 2>&1 | grep … | head` on mac-2 hung from 2026-11-27 15:33 for 20 hours. The xtask failed early and left its QEMU behind, orphaned to launchd but still in the command's process group, with its stderr the pipe into grep (lsof: qemu 37687 fd 2 -> grep 37671 fd 0). grep never saw end of input, the open session renewed the lease, and the agent's background command never ended, so nothing woke the session. Not the VM sleeping, not the sync, not a lock. `midas node session` now runs an agent's command in its own process group with its output relayed through midas (stall.rs): - no output and under 1 s of CPU a minute for the group: said on stderr at 15 minutes, the group stopped at 30 (SIGTERM, SIGKILL 10 s on), unless another command on the node moved lately; the ssh then ends, which is what wakes an idle Claude Code session; - once the command ends, what it left holding its output gets two seconds, then the session ends and names it (`ssh node 'x &'` hung too); - MIDAS_STALL=off or =2h as the first word for a command meant to wait. The heartbeat reports each running command's quiet time, and the session's node line on the page says "its command has done nothing for …" instead of "building now" from five minutes on. Reproduced on deck-1 through real sshd with the installed midas: s857's shape hung 901 s (the orphan's whole life), `sleep 45 & echo` 45 s. With this branch's node session: stopped and returned after 62 s (60 s test limit), 4 s, and a command printing every 6 s ran untouched.
DESIGN.md | 11 ++
docs/usage.md | 9 ++
src/board.rs | 8 ++
src/main.rs | 1 +
src/node.rs | 66 ++++++++-
src/procs.rs | 71 +++++++++-
src/session-start.md | 5 +-
src/stall.rs | 289 ++++++++++++++++++++++++++++++++++++++++
web/src/components/nodeline.tsx | 10 ++
web/src/lib/nodeline.test.ts | 9 +-
web/src/lib/nodeline.ts | 6 +-
web/src/lib/stream.ts | 2 +
12 files changed, 476 insertions(+), 11 deletions(-)
diff --git a/DESIGN.md b/DESIGN.md
index 6548758..65d8cd9 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -82,6 +82,17 @@ midas release # or the session-end hook does it
renews the lease, so a long build is never cut short; so does a bot lease's
running bot); a node that stops
reporting is given back after two hours.
+- **An open session is not use when nothing runs in it** (`stall.rs`). s857's
+ pipeline on mac-2 waited 20 hours on a pipe held open by a QEMU its xtask
+ had orphaned, which renewed the lease and kept the agent waiting for a
+ command that would never end (2026-11-27). So an agent's command runs in
+ its own process group with its output relayed through midas: quiet — no
+ output, under a second of CPU a minute for the group — for 30 minutes, the
+ group is stopped, unless another command on the node is moving; and once
+ the command ends, what it left holding its output gets two seconds, not
+ the session. A background command ending is what wakes an idle agent, so
+ stopping it is also how the session hears. Terminal sessions, file
+ transfers and a bot's relay are not watched.
- **Builds do not run where agents are**: `cargo` there is midas and names the
`ssh` to use instead (`MIDAS_LOCAL_BUILD=1` for a one-off); commands that only
read the manifest (fmt, metadata, tree…) pass through.
diff --git a/docs/usage.md b/docs/usage.md
index 7099e54..83e1054 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -44,6 +44,15 @@ midas release # give it back
while a deploy of what landed waits for it — and when an agent session
ends. `midas intent "…" --minutes N` keeps it for that long. A deploy is
first in every line, ahead of the sessions that asked before it.
+- **A command that does nothing is stopped.** No output and next to no CPU
+ for 15 minutes is said on its stderr; for 30, its whole process group is
+ stopped (unless another command on the node is moving, as a build another
+ cargo waits for is), so the ssh ends and the agent hears of it. One meant to
+ wait takes `MIDAS_STALL=off`, or a limit such as `MIDAS_STALL=2h`, as its
+ first word. A command that ended no longer leaves its ssh open behind a
+ process it started that still holds its output (`ssh node 'server &'`): the
+ session ends two seconds after it and names what it left. The session's
+ node line on the page says when its command has done nothing for five minutes.
- **Only the holder gets in.** ssh to a node your worktree does not hold is
refused, with the reason. `cargo` refuses to build outside a node and says
which `midas run` (or, on a node you hold, which `ssh`) to use (`MIDAS_LOCAL_BUILD=1` for a one-off).
diff --git a/src/board.rs b/src/board.rs
index a3e7acb..0a65439 100644
--- a/src/board.rs
+++ b/src/board.rs
@@ -37,6 +37,8 @@ use crate::registry::now;
const WORKING_S: i64 = 12 * 3600;
/// A landed session stays in the last column this long.
const LANDED_S: i64 = 86400;
+/// A command on a session's node quiet this long is shown as quiet, not as building.
+const QUIET_S: u64 = 300;
pub type Entities = BTreeMap<String, Value>;
@@ -159,6 +161,12 @@ pub fn compose(state: &Value, sessions: &[Value], names: &Value, decisions: &Val
c["gate"] = json!(o.starts_with("gate-"));
// A command running on its node now (an ssh session open there).
c["busy"] = json!(n["reading"]["sessions"].as_u64().unwrap_or(0) > 0);
+ // …and when that command has printed nothing and used no CPU for
+ // five minutes or more (stall.rs): s857's showed "building now" for
+ // 19 hours while it waited on a pipe nothing would close.
+ c["quiet"] = r["commands"].as_array().into_iter().flatten()
+ .filter(|x| x["quiet_s"].as_u64().is_some_and(|q| q >= QUIET_S))
+ .max_by_key(|x| x["quiet_s"].as_u64()).cloned().unwrap_or(Value::Null);
c["node_gate"] = json!(o.starts_with("gate-"));
}
}
diff --git a/src/main.rs b/src/main.rs
index d90c482..046a52b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -58,6 +58,7 @@ mod setup_macos;
mod stats;
mod store;
mod sshcfg;
+mod stall;
mod talks;
mod tap;
mod templates;
diff --git a/src/node.rs b/src/node.rs
index ffa7cc3..19a9813 100644
--- a/src/node.rs
+++ b/src/node.rs
@@ -338,6 +338,8 @@ pub fn reading() -> Value {
// Open ssh sessions: a lease with none for half an hour is given back
// (the hub's idle rule), one with a long build running is not.
"sessions": ssh_sessions(),
+ // What those sessions run, and how long each has done nothing (stall.rs).
+ "commands": quiet_commands(),
// A bot running here (`midas node bot`): for a bot lease, as good as a
// session open.
"bot": crate::bot::reading(),
@@ -620,7 +622,45 @@ pub fn session() -> Result<i32> {
let _ = fs::write(&m, command_for_log.as_deref().unwrap_or(""));
m
});
- let status = cmd.status();
+ // An agent's command, its output not a terminal: watched, so one that does
+ // nothing cannot hold the session for ever (stall.rs). A terminal session
+ // stays in sshd's own process group, where job control expects it.
+ // SAFETY: isatty(3) only asks about a descriptor.
+ let tty = unsafe { libc::isatty(0) == 1 || libc::isatty(1) == 1 };
+ let watch = running.as_ref().filter(|_| !tty).and(original.as_deref()).and_then(crate::stall::limits_for);
+ let status = match watch {
+ Some(limits) => {
+ let what = command_for_log.as_deref().unwrap_or("").chars().take(80).collect::<String>();
+ crate::stall::run(cmd, limits, running.as_deref(), || others_moving(running.as_deref(), limits), |said| {
+ use crate::stall::Said;
+ let mins = |d: Duration| match d.as_secs() { s if s < 120 => format!("{s} s"), s => format!("{} minutes", s / 60) };
+ match said {
+ Said::Quiet(q) => {
+ eprintln!("midas: `{what}` has printed nothing and used no CPU for {} on {}; it is \
+ stopped at {} of it unless it moves (MIDAS_STALL=off as its first word lets it be).",
+ mins(q), cfg.node, mins(limits.stop));
+ emit(&cfg, "stalled", json!({"stage": "warn", "actor": actor, "command": command_for_log, "quiet_s": q.as_secs()}));
+ }
+ Said::Stopping(q, left) => {
+ eprintln!("midas: stopped `{what}` on {}: nothing printed and no CPU used for {} — \
+ it waits for something that will not come (a process it started holding a pipe \
+ open, a lock, a prompt). Run it again with what it waited for fixed.",
+ cfg.node, mins(q));
+ emit(&cfg, "stalled", json!({"stage": "stop", "actor": actor, "command": command_for_log,
+ "quiet_s": q.as_secs(), "group": left}));
+ }
+ Said::Leftovers(held) => {
+ eprintln!("midas: `{what}` ended, but left {} process(es) holding its output open ({}); the \
+ session ends without them. Start one meant to outlive the command with its output \
+ redirected: nohup … >/tmp/x.log 2>&1 &",
+ held.len(), held.join("; "));
+ emit(&cfg, "left_running", json!({"actor": actor, "command": command_for_log, "held": held}));
+ }
+ }
+ })
+ }
+ None => cmd.status(),
+ };
if let Some(m) = running {
let _ = fs::remove_file(m);
}
@@ -715,6 +755,30 @@ fn running_in(dir: &Path) -> Vec<String> {
}).collect()
}
+/// The commands running here and how long each has been quiet: its marker's
+/// age, which the stall watch touches at every sign of progress (stall.rs).
+/// For the heartbeat, so the page can say a session's command does nothing.
+fn quiet_commands() -> Vec<Value> {
+ let now = std::time::SystemTime::now();
+ running_commands(); // clears the markers of sessions that are gone
+ fs::read_dir(RUNNING).into_iter().flatten().flatten().filter_map(|e| {
+ let quiet = now.duration_since(e.metadata().ok()?.modified().ok()?).ok()?;
+ Some(json!({"command": fs::read_to_string(e.path()).ok()?.chars().take(120).collect::<String>(), "quiet_s": quiet.as_secs()}))
+ }).collect()
+}
+
+/// Whether another command running here moved lately: a quiet cargo may be
+/// waiting for the build directory's lock while the build that holds it works.
+fn others_moving(mine: Option<&Path>, limits: crate::stall::Limits) -> bool {
+ let lately = (limits.stop / 5).min(Duration::from_secs(120));
+ let now = std::time::SystemTime::now();
+ running_commands();
+ fs::read_dir(RUNNING).into_iter().flatten().flatten()
+ .filter(|e| Some(e.path().as_path()) != mine)
+ .filter_map(|e| now.duration_since(e.metadata().ok()?.modified().ok()?).ok())
+ .any(|age| age < lately)
+}
+
/// The cgroup's OOM-kill count (the node's own memory limit, not the host's).
fn oom_kills() -> u64 {
fs::read_to_string("/sys/fs/cgroup/memory.events")
diff --git a/src/procs.rs b/src/procs.rs
index b72ab9c..48960eb 100644
--- a/src/procs.rs
+++ b/src/procs.rs
@@ -1,10 +1,16 @@
//! The processes on this machine, on Linux (from `/proc`) and on macOS (from
-//! `ps`), for the node's handover and its count of open ssh sessions.
+//! `ps`), for the node's handover, its count of open ssh sessions, and the
+//! stall watch on a command (`node::watch`).
pub struct Proc {
pub pid: u32,
pub ppid: u32,
pub uid: u32,
+ /// Its process group: a command and everything it started, even what was
+ /// orphaned to init on the way, unless that left the group on purpose.
+ pub pgid: u32,
+ /// CPU time used so far, user and system, in milliseconds.
+ pub cpu_ms: u64,
/// The full command line, arguments joined by spaces.
pub cmd: String,
}
@@ -12,6 +18,8 @@ pub struct Proc {
#[cfg(target_os = "linux")]
pub fn all() -> Vec<Proc> {
use std::fs;
+ // SAFETY: sysconf has no preconditions.
+ let tick = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }.max(1) as u64;
let mut out = Vec::new();
let Ok(rd) = fs::read_dir("/proc") else { return out };
for e in rd.flatten() {
@@ -21,23 +29,62 @@ pub fn all() -> Vec<Proc> {
let cmd = fs::read(format!("/proc/{pid}/cmdline")).unwrap_or_default()
.split(|b| *b == 0).filter(|a| !a.is_empty()).map(|a| String::from_utf8_lossy(a).to_string())
.collect::<Vec<_>>().join(" ");
- out.push(Proc { pid, ppid: field("PPid:").unwrap_or(0), uid: field("Uid:").unwrap_or(u32::MAX), cmd });
+ let (pgid, ticks) = fs::read_to_string(format!("/proc/{pid}/stat")).ok().and_then(|s| stat_fields(&s)).unwrap_or((0, 0));
+ out.push(Proc {
+ pid, ppid: field("PPid:").unwrap_or(0), uid: field("Uid:").unwrap_or(u32::MAX),
+ pgid, cpu_ms: ticks * 1000 / tick, cmd,
+ });
}
out
}
+/// `/proc/<pid>/stat`'s process group and CPU ticks (utime + stime). The
+/// fields are counted after the command's closing parenthesis, since the
+/// command itself may hold spaces and parentheses.
+#[cfg(any(target_os = "linux", test))]
+fn stat_fields(stat: &str) -> Option<(u32, u64)> {
+ let rest = &stat[stat.rfind(')')? + 1..];
+ let f: Vec<&str> = rest.split_whitespace().collect();
+ // After the command: state(0) ppid(1) pgrp(2) … utime(11) stime(12).
+ Some((f.get(2)?.parse().ok()?, f.get(11)?.parse::<u64>().ok()? + f.get(12)?.parse::<u64>().ok()?))
+}
+
#[cfg(not(target_os = "linux"))]
pub fn all() -> Vec<Proc> {
- let Ok(out) = std::process::Command::new("ps").args(["-axo", "pid=,ppid=,uid=,command="]).output() else {
+ let Ok(out) = std::process::Command::new("ps").args(["-axo", "pid=,ppid=,uid=,pgid=,time=,command="]).output() else {
return vec![];
};
String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| {
let mut w = l.split_whitespace();
- let (pid, ppid, uid) = (w.next()?.parse().ok()?, w.next()?.parse().ok()?, w.next()?.parse().ok()?);
- Some(Proc { pid, ppid, uid, cmd: w.collect::<Vec<_>>().join(" ") })
+ let (pid, ppid, uid, pgid) = (w.next()?.parse().ok()?, w.next()?.parse().ok()?, w.next()?.parse().ok()?, w.next()?.parse().ok()?);
+ let cpu_ms = cpu_time_ms(w.next()?).unwrap_or(0);
+ Some(Proc { pid, ppid, uid, pgid, cpu_ms, cmd: w.collect::<Vec<_>>().join(" ") })
}).collect()
}
+/// `ps`'s `time`, `[[dd-]hh:]mm:ss[.cc]` (macOS: `2369:57.86`, minutes past
+/// sixty), in milliseconds.
+#[cfg(any(not(target_os = "linux"), test))]
+fn cpu_time_ms(t: &str) -> Option<u64> {
+ let (days, clock) = match t.split_once('-') {
+ Some((d, c)) => (d.parse::<u64>().ok()?, c),
+ None => (0, t),
+ };
+ let mut parts: Vec<&str> = clock.split(':').collect();
+ let secs: f64 = parts.pop()?.parse().ok()?;
+ let mut whole = 0u64;
+ for p in parts {
+ whole = whole * 60 + p.parse::<u64>().ok()?;
+ }
+ Some(((days * 86400 + whole * 60) as f64 * 1000.0 + secs * 1000.0).round() as u64)
+}
+
+/// The CPU time, in milliseconds, used so far by the processes in group
+/// `pgid`, but not by `except` (the watcher itself, should it be in it).
+pub fn group_cpu_ms(all: &[Proc], pgid: u32, except: u32) -> u64 {
+ all.iter().filter(|p| p.pgid == pgid && p.pid != except).map(|p| p.cpu_ms).sum()
+}
+
/// This process and its ancestors.
pub fn ancestry(all: &[Proc]) -> std::collections::HashSet<u32> {
let mut seen = std::collections::HashSet::new();
@@ -69,7 +116,19 @@ mod tests {
use super::*;
fn p(pid: u32, ppid: u32, cmd: &str) -> Proc {
- Proc { pid, ppid, uid: 1000, cmd: cmd.into() }
+ Proc { pid, ppid, uid: 1000, pgid: pid, cpu_ms: 0, cmd: cmd.into() }
+ }
+
+ #[test]
+ fn cpu_time_reads_both_platforms_forms() {
+ assert_eq!(cpu_time_ms("0:00.01"), Some(10));
+ assert_eq!(cpu_time_ms("2369:57.86"), Some(142_197_860)); // mac-2's configd
+ assert_eq!(cpu_time_ms("01:02:03"), Some(3_723_000));
+ assert_eq!(cpu_time_ms("1-00:00:01"), Some(86_401_000));
+ assert_eq!(cpu_time_ms("bad"), None);
+ // A command whose name has a space and a parenthesis in it.
+ let stat = "37664 (qemu (x) y) S 1 37603 37603 0 -1 4194560 1 0 0 0 1234 66 0 0 20 0";
+ assert_eq!(stat_fields(stat), Some((37603, 1300)));
}
#[test]
diff --git a/src/session-start.md b/src/session-start.md
index e3a6d23..bce3d8d 100644
--- a/src/session-start.md
+++ b/src/session-start.md
@@ -25,7 +25,10 @@ If none is free, `midas take` waits 90 s and then exits 75 with your place in
line kept: run `midas wait` **in the background** to get the node when it
frees. A node with no ssh session open for 30 minutes goes back to the pool;
the session-end hook gives it back too. `midas status` shows who holds what,
-`midas log` what happened.
+`midas log` what happened. A command there that prints nothing and uses no
+CPU for 30 minutes is stopped, which ends your ssh and says why
+(`MIDAS_STALL=off` or `=2h` as its first word for one meant to wait), and a
+process left behind holding a command's output no longer keeps its ssh open.
**Subagents.** A subagent in this worktree shares its node: it can `ssh` there
too, but every ssh first re-syncs the node, so two agents running commands
diff --git a/src/stall.rs b/src/stall.rs
new file mode 100644
index 0000000..acc636e
--- /dev/null
+++ b/src/stall.rs
@@ -0,0 +1,289 @@
+//! 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 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));
+ }
+
+ /// 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:?}");
+ }
+}
diff --git a/web/src/components/nodeline.tsx b/web/src/components/nodeline.tsx
index a81d5db..a839a49 100644
--- a/web/src/components/nodeline.tsx
+++ b/web/src/components/nodeline.tsx
@@ -125,6 +125,16 @@ export function nodeFoot(s: Hosted): m.Vnode | null {
const n = nodeLine(c, $s.workspace?.leases, now())
if (!c || !n) return null
if (n.kind === 'on') {
+ if (n.quiet) {
+ return (
+ <div key="node" class="msg__node msg__node--waits msg__node--long" title={n.quiet.command}>
+ <span class="msg__node-k">Node</span>
+ <span class="msg__node-v">
+ On <b>{n.node}</b> · its command has done nothing for {span(n.quiet.quiet_s)}: no output, no CPU. midas stops it at 30 minutes, which tells the session.
+ </span>
+ </div>
+ )
+ }
const what = n.busy ? 'building now' : n.idle_s == null || n.idle_s < 60 ? 'idle' : `idle ${span(n.idle_s)}`
return (
<div key="node" class={`msg__node${n.busy ? ' msg__node--busy' : ''}`} title={n.since ? `held since ${age(n.since)} ago; it goes back to the pool after 30 minutes with no ssh session` : undefined}>
diff --git a/web/src/lib/nodeline.test.ts b/web/src/lib/nodeline.test.ts
index 7c04dad..5058cff 100644
--- a/web/src/lib/nodeline.test.ts
+++ b/web/src/lib/nodeline.test.ts
@@ -18,7 +18,14 @@ const NODES = [
test('on a node: building while a command runs there, else idle since its lease was last renewed', () => {
expect(nodeLine(card({stage: 'on_node', node: 'mac-1', busy: true}), {'mac-1': lease(500)}, 1000)).toMatchObject({kind: 'on', node: 'mac-1', busy: true, idle_s: 0})
- expect(nodeLine(card({stage: 'on_node', node: 'vps-1'}), {'vps-1': lease(520)}, 1000)).toMatchObject({kind: 'on', busy: false, idle_s: 480})
+ expect(nodeLine(card({stage: 'on_node', node: 'vps-1'}), {'vps-1': lease(520)}, 1000)).toMatchObject({kind: 'on', busy: false, idle_s: 480, quiet: null})
+})
+
+test('a command that runs but does nothing is quiet, not building', () => {
+ const quiet = {command: 'cargo clippy … | grep … | head', quiet_s: 1200}
+ expect(nodeLine(card({stage: 'on_node', node: 'mac-2', busy: true, quiet}), {'mac-2': lease(500)}, 1000)).toMatchObject({kind: 'on', busy: true, quiet})
+ // A reading from before the command ended says nothing about now.
+ expect(nodeLine(card({stage: 'on_node', node: 'mac-2', busy: false, quiet}), {'mac-2': lease(500)}, 1000)).toMatchObject({quiet: null})
})
test('in line for a node, with who holds those it may take; its gate waiting is To live, not this', () => {
diff --git a/web/src/lib/nodeline.ts b/web/src/lib/nodeline.ts
index aa46afb..80b059c 100644
--- a/web/src/lib/nodeline.ts
+++ b/web/src/lib/nodeline.ts
@@ -8,7 +8,7 @@ import type {BoardCard, BoardNode, LogItem, NodeHeld} from '@/lib/stream'
*/
export type NodeLine =
| {kind: 'waits'; wants: string; position: number; since: number; held: NodeHeld[]}
- | {kind: 'on'; node: string; busy: boolean; idle_s: number | null; since: number | null}
+ | {kind: 'on'; node: string; busy: boolean; idle_s: number | null; since: number | null; quiet: {command: string; quiet_s: number} | null}
/** A session's node line from its card and the leases; null while it neither holds nor waits for one. */
export function nodeLine(c: BoardCard | undefined, leases: Record<string, Lease> | undefined, t: number): NodeLine | null {
@@ -17,7 +17,9 @@ export function nodeLine(c: BoardCard | undefined, leases: Record<string, Lease>
const l = leases?.[c.node]
// A command running there is use, however long since the lease was renewed (home.tsx `blocker`).
const idle_s = c.busy ? 0 : l ? Math.max(0, t - l.renewed_at) : null
- return {kind: 'on', node: c.node, busy: !!c.busy, idle_s, since: c.since}
+ // Running but doing nothing is not building (s857's showed "building now" for 19 hours).
+ const quiet = c.busy && c.quiet ? c.quiet : null
+ return {kind: 'on', node: c.node, busy: !!c.busy, idle_s, since: c.since, quiet}
}
const w = c.node_wait
if (w && !w.gate) return {kind: 'waits', wants: w.wants, position: w.position, since: w.since, held: w.held ?? []}
diff --git a/web/src/lib/stream.ts b/web/src/lib/stream.ts
index 22abb47..9704c46 100644
--- a/web/src/lib/stream.ts
+++ b/web/src/lib/stream.ts
@@ -48,6 +48,8 @@ export interface BoardCard {
node_wait?: NodeWait | null
/** A command is running on its node now. */
busy?: boolean
+ /** That command has printed nothing and used no CPU for `quiet_s` (five minutes or more); midas stops it at thirty. */
+ quiet?: {command: string; quiet_s: number} | null
step?: string | null
sha?: string | null
/** Landed, and every target deployed after landings serves it (ship.rs). */