Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
29t: when memory runs out, the bot's command goes first, not kwant (#852)
Oleksandr Ivanchenko95c56004aa3a
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 5b0ec717..e1e93bd8 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -71,15 +71,36 @@ fn kill_group(pid: Option<u32>) {/// Starts the CLI as the leader of its own process group, for [`ProcessGroup`]./// On Windows the CLI gets no console window of its own (`CREATE_NO_WINDOW`); its tree is held/// by the Job Object [`ProcessGroup::of`] puts it in.+/// On Linux it is also first in line when memory runs out ([`OOM_FIRST`]): a runaway build a+/// bot started is stopped before kwnt is.pub(crate) fn own_process_group(cmd: &mut Command) {#[cfg(unix)]cmd.process_group(0);+ #[cfg(target_os = "linux")]+ // SAFETY: open(2), write(2) and close(2) are async-signal-safe; the path and value are+ // static, so nothing is allocated or touched in this process's memory+ unsafe {+ cmd.pre_exec(|| {+ // Raising one's own score needs no privilege; a missing /proc is fine too+ let fd = libc::open(c"/proc/self/oom_score_adj".as_ptr(), libc::O_WRONLY | libc::O_CLOEXEC);+ if fd >= 0 {+ libc::write(fd, OOM_FIRST.as_ptr().cast(), OOM_FIRST.len());+ libc::close(fd);+ }+ Ok(())+ });+ }#[cfg(windows)]cmd.creation_flags(CREATE_NO_WINDOW);#[cfg(not(any(unix, windows)))]let _ = cmd;}+/// Written to `/proc/self/oom_score_adj` of everything kwant starts on the host: the highest+/// score, inherited by all it starts, so the kernel stops the bot's work before kwnt.+#[cfg(target_os = "linux")]+const OOM_FIRST: &[u8] = b"1000";+/// `CREATE_NO_WINDOW`: a console program started by the (windowless) app opens no console window.#[cfg(windows)]const CREATE_NO_WINDOW: u32 = 0x0800_0000;@@ -3329,3 +3350,19 @@ endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\n}}}++#[cfg(all(test, target_os = "linux"))]+mod oom_tests {+ use super::*;++ // Covers the CLI spawns (claude, codex, grok…): they go through own_process_group too+ #[tokio::test]+ async fn a_cli_started_in_its_own_group_is_first_when_memory_runs_out() {+ let mut cmd = Command::new("cat");+ cmd.arg("/proc/self/oom_score_adj").stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());+ own_process_group(&mut cmd);+ let out = cmd.output().await.unwrap();+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));+ assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "1000");+ }+}diff --git a/src/tools/shell.rs b/src/tools/shell.rsindex d0fe0188..136a13fa 100644--- a/src/tools/shell.rs+++ b/src/tools/shell.rs@@ -32,6 +32,8 @@ pub async fn execute_shell_env(workspace: &Path, args: &Value, env: &[(String, Scmd.kill_on_drop(true);own_process_group(&mut cmd);+ // Read before the spawn: a kill the system made while the command ran raises it+ let oom_before = oom_kills();let mut child = cmd.spawn().map_err(|e| ToolError::Execution(format!("Failed to execute shell: {}", e)))?;@@ -74,16 +76,70 @@ pub async fn execute_shell_env(workspace: &Path, args: &Value, env: &[(String, Slet status = status.map_err(|e| ToolError::Execution(format!("Failed to execute shell: {}", e)))?;let stdout = String::from_utf8_lossy(&stdout).to_string();- let stderr = String::from_utf8_lossy(&stderr).to_string();+ let mut stderr = String::from_utf8_lossy(&stderr).to_string();let exit_code = status.code().unwrap_or(-1);+ #[cfg(unix)]+ let signal = std::os::unix::process::ExitStatusExt::signal(&status);+ #[cfg(not(unix))]+ let signal: Option<i32> = None;+ // kwant's own timeout returned above, so a kill seen here came from outside the command+ let oom_after = if signal == Some(KILLED) { oom_kills() } else { None };+ if let Some(note) = killed_note(signal, oom_before, oom_after) {+ if !stderr.is_empty() && !stderr.ends_with('\n') {+ stderr.push('\n');+ }+ stderr.push_str(note);+ stderr.push('\n');+ }- Ok(json!({+ let mut out = json!({"command": command_str,"stdout": stdout,"stderr": stderr,"exit_code": exit_code,"success": status.success()- }))+ });+ if let Some(n) = signal {+ out["signal"] = json!(n);+ }+ Ok(out)+}++/// SIGKILL: what the out-of-memory killer sends, and what nothing can catch.+const KILLED: i32 = 9;++/// Told to the bot when the system stopped its command for lack of memory.+pub const OOM_KILLED: &str = "kwant: the computer ran out of memory, so the system stopped this command and everything it started. kwant kept running. Try a smaller job (for example fewer parallel build jobs).";++/// Told to the bot when something else killed its command.+pub const KILLED_FROM_OUTSIDE: &str = "kwant: this command was killed (signal 9) by something outside it.";++/// The line added to stderr for a command that ended on `signal`: only a SIGKILL gets one, and+/// it says out of memory when the system's OOM-kill count went up while the command ran. The+/// count is system-wide, so another process's kill at the same moment would read the same;+/// that is rare enough here. With no count (not Linux, /proc unreadable) it is the outside line.+pub fn killed_note(signal: Option<i32>, oom_before: Option<u64>, oom_after: Option<u64>) -> Option<&'static str> {+ if signal != Some(KILLED) {+ return None;+ }+ match (oom_before, oom_after) {+ (Some(before), Some(after)) if after > before => Some(OOM_KILLED),+ _ => Some(KILLED_FROM_OUTSIDE),+ }+}++/// How many processes the kernel's out-of-memory killer has stopped since boot (`oom_kill` in+/// /proc/vmstat); None outside Linux or when it can't be read.+fn oom_kills() -> Option<u64> {+ #[cfg(target_os = "linux")]+ return vmstat_oom_kills(&std::fs::read_to_string("/proc/vmstat").ok()?);+ #[cfg(not(target_os = "linux"))]+ None+}++#[cfg(any(target_os = "linux", test))]+fn vmstat_oom_kills(vmstat: &str) -> Option<u64> {+ vmstat.lines().find_map(|l| l.strip_prefix("oom_kill ")).and_then(|n| n.trim().parse().ok())}/// The bash that runs bot commands. On Windows this is Git for Windows' `bash.exe`, never@@ -198,3 +254,33 @@ mod windows_path_tests {assert!(GIT_MISSING.contains("winget install --id Git.Git -e"));}}++#[cfg(test)]+mod killed_tests {+ use super::*;++ #[test]+ fn a_kill_while_the_oom_count_rose_says_out_of_memory_and_any_other_kill_says_outside() {+ assert_eq!(killed_note(Some(9), Some(3), Some(4)), Some(OOM_KILLED));+ assert_eq!(killed_note(Some(9), Some(3), Some(3)), Some(KILLED_FROM_OUTSIDE));+ // No count to compare (not Linux, /proc unreadable): never a guess at memory+ assert_eq!(killed_note(Some(9), None, Some(4)), Some(KILLED_FROM_OUTSIDE));+ assert_eq!(killed_note(Some(9), Some(3), None), Some(KILLED_FROM_OUTSIDE));+ assert_eq!(killed_note(Some(9), None, None), Some(KILLED_FROM_OUTSIDE));+ // A normal exit, or another signal (SIGTERM, SIGSEGV), gets no line+ assert_eq!(killed_note(None, Some(3), Some(4)), None);+ assert_eq!(killed_note(Some(15), Some(3), Some(4)), None);+ assert_eq!(killed_note(Some(11), None, None), None);+ assert!(OOM_KILLED.contains("ran out of memory") && OOM_KILLED.contains("kwant kept running"));+ assert!(KILLED_FROM_OUTSIDE.contains("signal 9"));+ }++ #[test]+ fn the_oom_kill_count_is_read_from_vmstat() {+ assert_eq!(vmstat_oom_kills("pgfault 12\noom_kill 7\nnr_free_pages 1\n"), Some(7));+ // oom_kill_x is another counter; a missing line or a non-number is no count+ assert_eq!(vmstat_oom_kills("oom_kill_x 7\n"), None);+ assert_eq!(vmstat_oom_kills("oom_kill x\n"), None);+ assert_eq!(vmstat_oom_kills(""), None);+ }+}diff --git a/tests/shell_tool_test.rs b/tests/shell_tool_test.rsindex 5257d60c..91eecc4f 100644--- a/tests/shell_tool_test.rs+++ b/tests/shell_tool_test.rs@@ -57,3 +57,40 @@ async fn a_finished_command_still_returns_its_output() {assert_eq!(v["exit_code"], 3);assert_eq!(v["success"], false);}++// Everything a bot runs on the host is first in line when memory runs out, so a runaway build+// is stopped before kwnt is; whatever the command starts inherits it.+#[cfg(target_os = "linux")]+#[tokio::test]+async fn a_bot_command_and_what_it_starts_go_first_when_memory_runs_out() {+ let tmp = tempdir().unwrap();+ let args = json!({ "command": "cat /proc/self/oom_score_adj; bash -c 'cat /proc/self/oom_score_adj'" });+ let v = execute_shell(tmp.path(), &args).await.unwrap();+ assert_eq!(v["exit_code"], 0, "{v}");+ assert_eq!(v["stdout"], "1000\n1000\n", "{v}");+}++// A command killed from outside says so, and keeps exit_code -1 for existing readers. kwnt's+// own timeout is not a kill seen here (it is an error, tested above).+#[cfg(unix)]+#[tokio::test]+async fn a_command_killed_from_outside_is_told_why() {+ let tmp = tempdir().unwrap();+ let args = json!({ "command": "echo before >&2; kill -9 $$" });+ let v = execute_shell(tmp.path(), &args).await.unwrap();+ assert_eq!(v["signal"], 9, "{v}");+ assert_eq!(v["exit_code"], -1, "{v}");+ assert_eq!(v["success"], false, "{v}");+ let stderr = v["stderr"].as_str().unwrap();+ assert!(stderr.starts_with("before\n"), "{stderr}");+ assert!(stderr.contains(kwnt::tools::shell::KILLED_FROM_OUTSIDE), "{stderr}");+ assert!(!stderr.contains("ran out of memory"), "{stderr}");+}++#[tokio::test]+async fn a_normal_exit_has_no_signal() {+ let tmp = tempdir().unwrap();+ let v = execute_shell(tmp.path(), &json!({ "command": "exit 0" })).await.unwrap();+ assert!(v.get("signal").is_none(), "{v}");+ assert_eq!(v["stderr"], "", "{v}");+}