diff --git a/crates/forge-ci/src/proto.rs b/crates/forge-ci/src/proto.rs index 5453a50..843ece5 100644 --- a/crates/forge-ci/src/proto.rs +++ b/crates/forge-ci/src/proto.rs @@ -238,6 +238,15 @@ pub struct FinishRequest { pub outcome: Outcome, pub exit_code: Option, pub message: Option, + /// True when the OOM killer killed a process in the job's cgroup, read from its + /// `memory.events`. This is what shows an OOM kill that the job survived: cargo reports a + /// killed rustc in the log and exits 101. Absent from an older runner, from a runner that + /// cannot read the cgroup, and when nothing was killed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub oom_killed: Option, + /// How many processes the OOM killer took in the job's cgroup (`oom_kill`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub oom_kills: Option, } /// Final result of a job, reported by the runner. @@ -301,14 +310,28 @@ mod tests { outcome: Outcome::Failure, exit_code: Some(2), message: None, + oom_killed: None, + oom_kills: None, }; let json = serde_json::to_string(&req).unwrap(); + // An old runner's body, and a new runner that saw no OOM kill, look the same. assert_eq!( json, r#"{"outcome":"failure","exit_code":2,"message":null}"# ); let back: FinishRequest = serde_json::from_str(&json).unwrap(); assert_eq!(back, req); + let oom = FinishRequest { + oom_killed: Some(true), + oom_kills: Some(2), + ..req + }; + let json = serde_json::to_string(&oom).unwrap(); + assert!( + json.contains(r#""oom_killed":true,"oom_kills":2"#), + "{json}" + ); + assert_eq!(serde_json::from_str::(&json).unwrap(), oom); } #[test] diff --git a/crates/forge-core/migrations/0060_runner_memory.sql b/crates/forge-core/migrations/0060_runner_memory.sql index e23bf69..09d23e6 100644 --- a/crates/forge-core/migrations/0060_runner_memory.sql +++ b/crates/forge-core/migrations/0060_runner_memory.sql @@ -5,3 +5,7 @@ ALTER TABLE ci_runners ADD COLUMN reported_memory_budget INTEGER NULL; ALTER TABLE ci_runners ADD COLUMN reported_memory_free INTEGER NULL; ALTER TABLE ci_runners ADD COLUMN reported_memory_reserve INTEGER NULL; + +-- Processes the OOM killer took in a job's cgroup, as the runner read them from memory.events when +-- the job ended. NULL when the runner did not say or nothing was killed. +ALTER TABLE ci_jobs ADD COLUMN oom_kills INTEGER NULL; diff --git a/crates/forge-core/src/ci.rs b/crates/forge-core/src/ci.rs index 34436d3..e26d70e 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -526,6 +526,9 @@ pub struct CiJob { pub heartbeat_at: Option, pub cancel_requested: bool, pub log_bytes: i64, + /// Processes the OOM killer took in the job's cgroup, as its runner reported. `None` when the + /// runner did not say (an older runner) or nothing was killed. + pub oom_kills: Option, } /// An artifact uploaded by a job. The file itself is stored outside the database. diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index 6c0aef9..b28e3f0 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -24,7 +24,7 @@ use crate::time::{now_stamp, stamp_after, stamp_to_unix}; use crate::token::{generate_token, hash_token}; const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, message, queued_at, \ - started_at, finished_at, heartbeat_at, cancel_requested, log_bytes"; + started_at, finished_at, heartbeat_at, cancel_requested, log_bytes, oom_kills"; const RUN_COLS: &str = "id, repo_id, number, trigger, git_ref, commit_oid, pull_number, actor_id, \ state, config_error, created_at, finished_at"; const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, \ @@ -151,6 +151,7 @@ fn map_job(row: &Row) -> Result { heartbeat_at: col_opt_text(row, 11)?, cancel_requested: col_bool(row, 12)?, log_bytes: col_int(row, 13)?, + oom_kills: opt_u32(row, 14)?, }) } @@ -1109,6 +1110,21 @@ impl Store { .ok_or(Error::NotFound) } + /// Records the OOM kills a runner saw in the job's cgroup. Zero is stored as nothing. + pub async fn set_job_oom_kills(&self, job_id: &str, kills: u32) -> Result<()> { + if kills == 0 { + return Ok(()); + } + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE ci_jobs SET oom_kills = ?2 WHERE id = ?1", + (job_id.to_string(), i64::from(kills)), + ) + .await + .map_err(db_err)?; + Ok(()) + } + /// Adds to the job's log size. pub async fn add_log_bytes(&self, job_id: &str, n: i64) -> Result<()> { if n < 0 { @@ -2589,6 +2605,47 @@ mod tests { assert_eq!(next.0.name, "small"); } + #[tokio::test] + async fn oom_kills_are_stored_on_the_job() { + let fx = fixture().await; + create( + &fx.store, + &fx.repo.id, + &fx.tahinli.id, + &[job("build", &[], &[])], + false, + ) + .await; + let (claimed, _, _) = fx + .store + .claim_job(&bare_runner(&[])) + .await + .unwrap() + .unwrap(); + assert_eq!(claimed.oom_kills, None); + fx.store.set_job_oom_kills(&claimed.id, 0).await.unwrap(); + assert_eq!( + fx.store + .job_by_id(&claimed.id) + .await + .unwrap() + .unwrap() + .oom_kills, + None, + "zero is nothing" + ); + fx.store.set_job_oom_kills(&claimed.id, 2).await.unwrap(); + assert_eq!( + fx.store + .job_by_id(&claimed.id) + .await + .unwrap() + .unwrap() + .oom_kills, + Some(2) + ); + } + #[tokio::test] async fn claim_matches_labels_and_skips_disabled() { let fx = fixture().await; diff --git a/crates/forge-runner/src/executor.rs b/crates/forge-runner/src/executor.rs index 689169f..d09d684 100644 --- a/crates/forge-runner/src/executor.rs +++ b/crates/forge-runner/src/executor.rs @@ -31,6 +31,7 @@ use tokio_util::sync::CancellationToken; use crate::config::{Limits, RegistryConfig}; use crate::logs::forward_lines; use crate::oci::{ImageError, ImageStore, PreparedImage, RegistryAuth}; +use crate::oom::{OomEvents, OomSink}; use crate::sandbox::helper::EXIT_SETUP_FAILED; use crate::sandbox::idmap::{IdMap, remove_tree}; use crate::sandbox::{SandboxRequest, job_cgroup_path}; @@ -53,6 +54,9 @@ pub struct ExecRequest<'a> { pub logs: mpsc::Sender>, /// Cancelling this stops the job. The executor then reports `Outcome::Cancelled`. pub cancel: CancellationToken, + /// Where the executor leaves OOM kills it saw in the job's cgroup. Executors that cannot see + /// them leave it alone. + pub oom: OomSink, } /// The executor's answer. The runner adds timeouts and artifact results on top of it. @@ -308,15 +312,25 @@ struct Supervised { status: std::io::Result, /// The sandbox helper's last `forge-sandbox: ` line on stderr, when it printed one. sandbox_error: Option, + /// The OOM counters the helper printed, when something in the job was OOM-killed. + oom: Option, } /// Copies stderr lines to the log and remembers the last sandbox error line. async fn tap_sandbox_errors( mut lines: mpsc::Receiver>, logs: mpsc::Sender>, -) -> Option { +) -> (Option, Option) { let mut found = None; + let mut oom = None; while let Some(chunk) = lines.recv().await { + // The OOM line is for the runner, not for the job log. + if chunk.starts_with(SANDBOX_PREFIX) + && let Some(events) = OomEvents::from_line(&String::from_utf8_lossy(&chunk)) + { + oom = Some(events); + continue; + } let is_error = chunk.starts_with(SANDBOX_PREFIX) && !chunk[SANDBOX_PREFIX.len()..].starts_with(b"warning:"); if is_error { @@ -326,7 +340,7 @@ async fn tap_sandbox_errors( break; } } - found + (found, oom) } /// Forwards the child's output, waits for it, and reports how it ended. On cancellation the @@ -375,18 +389,19 @@ async fn supervise( reader.abort(); } } - let sandbox_error = match tap { + let (sandbox_error, oom) = match tap { Some(tap) => match tokio::time::timeout(READER_GRACE, tap).await { Ok(Ok(found)) => found, - _ => None, + _ => (None, None), }, - None => None, + None => (None, None), }; Supervised { cancelled, status, sandbox_error, + oom, } } @@ -586,6 +601,7 @@ impl BuiltinExecutor { workspace, logs, cancel, + oom: oom_sink, } = req; if let Err(e) = validate_job_id(&job.job_id) { return error_result(e.to_string()); @@ -660,6 +676,7 @@ impl BuiltinExecutor { cancelled, status, sandbox_error, + oom, } = supervise( child, logs, @@ -674,6 +691,9 @@ impl BuiltinExecutor { }), ) .await; + if let Some(events) = oom { + oom_sink.record(events); + } if cancelled { return cancelled_result(); } @@ -920,6 +940,7 @@ mod tests { workspace: &ws, logs: tx, cancel: CancellationToken::new(), + oom: OomSink::default(), }) .await; assert_eq!(result.outcome, Outcome::Success, "{result:?}"); diff --git a/crates/forge-runner/src/lib.rs b/crates/forge-runner/src/lib.rs index 7a2e587..89eb0ed 100644 --- a/crates/forge-runner/src/lib.rs +++ b/crates/forge-runner/src/lib.rs @@ -15,6 +15,7 @@ pub mod limiter; pub mod logs; pub mod memory; pub mod oci; +pub mod oom; pub mod restart; pub mod runner; pub mod sandbox; diff --git a/crates/forge-runner/src/oom.rs b/crates/forge-runner/src/oom.rs new file mode 100644 index 0000000..dcf50e6 --- /dev/null +++ b/crates/forge-runner/src/oom.rs @@ -0,0 +1,171 @@ +//! Out-of-memory kills inside a job's cgroup. The sandbox helper reads the cgroup's `memory.events` +//! when the job's init exits, before it deletes the cgroup, and prints one line on stderr. The +//! runner reads that line back and reports it when it finishes the job. +//! +//! Why the cgroup and not the exit code: when rustc is killed, cargo prints `(signal: 9, SIGKILL: +//! kill)` in the log and itself exits 101, so neither the job's exit code nor its message shows it. +//! +//! Kernel semantics (`Documentation/admin-guide/cgroup-v2.rst`): in `memory.events`, `oom` counts +//! how often the cgroup reached its limit and the OOM killer was invoked for it, and `oom_kill` +//! counts the processes of this cgroup that were killed by any kind of OOM killer. The victim's +//! cgroup is charged in `oom_kill_process`, so a victim of a host-wide OOM (global OOM killer, +//! nothing hit its own `memory.max`) is still counted in `oom_kill` of the cgroup it lived in, on +//! kernels since 4.13 that have the counter. `oom` stays 0 in that case, which is why both are +//! read and `oom_kill` is the one to trust. Both are hierarchical in `memory.events`, so a +//! process in a child cgroup counts too. A victim that was not in the job's cgroup at all (the +//! runner itself) is not counted, and nothing here can see it. + +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; + +/// The line the helper prints. It starts with the sandbox prefix, see `SANDBOX_PREFIX`. +pub const LINE_PREFIX: &str = "forge-sandbox: oom-events "; + +/// The `oom` and `oom_kill` counters of a job cgroup. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct OomEvents { + pub oom: u64, + pub oom_kill: u64, +} + +impl OomEvents { + /// Reads the counters from the text of a `memory.events` file. Missing keys count as 0. + pub fn parse_memory_events(text: &str) -> Self { + let mut events = Self::default(); + for line in text.lines() { + let mut parts = line.split_whitespace(); + let (Some(key), Some(value)) = (parts.next(), parts.next()) else { + continue; + }; + let value = value.parse().unwrap_or(0); + match key { + "oom" => events.oom = value, + "oom_kill" => events.oom_kill = value, + _ => {} + } + } + events + } + + /// True when something in the job was OOM-killed or the cgroup hit its limit. + pub fn any(&self) -> bool { + self.oom > 0 || self.oom_kill > 0 + } + + /// How many kills to report: `oom_kill`, or `oom` when only that one moved. + pub fn kills(&self) -> u32 { + u32::try_from(self.oom_kill.max(self.oom)).unwrap_or(u32::MAX) + } + + /// The stderr line for the runner, without a newline. + pub fn to_line(&self) -> String { + format!("{LINE_PREFIX}oom={} oom_kill={}", self.oom, self.oom_kill) + } + + /// Reads a line written by [`OomEvents::to_line`]. + pub fn from_line(line: &str) -> Option { + let rest = line.trim_end().strip_prefix(LINE_PREFIX)?; + let mut events = Self::default(); + for pair in rest.split_whitespace() { + let (key, value) = pair.split_once('=')?; + let value = value.parse().ok()?; + match key { + "oom" => events.oom = value, + "oom_kill" => events.oom_kill = value, + _ => {} + } + } + Some(events) + } +} + +/// Where an executor leaves the OOM kills it saw for a job. Cheap to clone and share. +#[derive(Clone, Debug, Default)] +pub struct OomSink(Arc); + +impl OomSink { + pub fn record(&self, events: OomEvents) { + if events.any() { + self.0.store(events.kills().max(1), Ordering::SeqCst); + } + } + + /// The reported kills, or `None` when nothing was killed or the executor cannot tell. + pub fn kills(&self) -> Option { + match self.0.load(Ordering::SeqCst) { + 0 => None, + n => Some(n), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const EVENTS: &str = "low 0\nhigh 0\nmax 12\noom 2\noom_kill 3\noom_group_kill 0\n"; + + #[test] + fn memory_events_are_parsed() { + let events = OomEvents::parse_memory_events(EVENTS); + assert_eq!( + events, + OomEvents { + oom: 2, + oom_kill: 3 + } + ); + assert!(events.any()); + assert_eq!(events.kills(), 3); + } + + #[test] + fn a_clean_cgroup_reports_nothing() { + let events = OomEvents::parse_memory_events("low 0\nhigh 0\nmax 4\noom 0\noom_kill 0\n"); + assert!(!events.any()); + assert_eq!(events.kills(), 0); + let sink = OomSink::default(); + sink.record(events); + assert_eq!(sink.kills(), None); + // Older kernels have no counters at all. + assert!(!OomEvents::parse_memory_events("low 0\nmax 1\n").any()); + assert!(!OomEvents::parse_memory_events("").any()); + } + + #[test] + fn a_host_wide_oom_shows_in_oom_kill_only() { + // The job's own limit was never reached, but its rustc was the global OOM victim. + let events = OomEvents::parse_memory_events("max 0\noom 0\noom_kill 1\n"); + assert!(events.any()); + assert_eq!(events.kills(), 1); + } + + #[test] + fn the_stderr_line_round_trips() { + let events = OomEvents { + oom: 1, + oom_kill: 2, + }; + assert_eq!( + events.to_line(), + "forge-sandbox: oom-events oom=1 oom_kill=2" + ); + assert_eq!(OomEvents::from_line(&events.to_line()), Some(events)); + assert_eq!(OomEvents::from_line("forge-sandbox: setup failed"), None); + assert_eq!( + OomEvents::from_line("forge-sandbox: oom-events oom=x"), + None + ); + } + + #[test] + fn the_sink_keeps_the_count() { + let sink = OomSink::default(); + let shared = sink.clone(); + shared.record(OomEvents { + oom: 0, + oom_kill: 2, + }); + assert_eq!(sink.kills(), Some(2)); + } +} diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index e454006..2ef1cf3 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -20,6 +20,7 @@ use crate::executor::{ExecRequest, ExecResult, Executor}; use crate::limiter::Limiter; use crate::logs::{self, PumpConfig}; use crate::memory::MemoryGate; +use crate::oom::OomSink; use crate::restart::{self, RestartState, Step}; use crate::update::{self, Installed, UpdateState}; use crate::workspace; @@ -342,6 +343,7 @@ impl Runner { }; let mut workspace_dir = None; + let oom = OomSink::default(); let prepared = workspace::prepare(&self.config.work_dir, &job, &self.config.url).await; let mut result = match prepared { Ok(dir) => { @@ -357,6 +359,7 @@ impl Runner { workspace: &dir, logs: tx.clone(), cancel: job_cancel.clone(), + oom: oom.clone(), }) .await; workspace_dir = Some(dir); @@ -408,6 +411,17 @@ impl Runner { if let Some(message) = &result.message { send_line(&tx, format!("runner: {message}")).await; } + let oom_kills = oom.kills(); + if let Some(kills) = oom_kills { + send_line( + &tx, + format!( + "runner: the out of memory killer killed {kills} process(es) in this job; \ + the job's memory is limited to its `memory` plus a little slack, see docs/ci.md" + ), + ) + .await; + } drop(tx); match pump.await { Ok(Ok(bytes)) => tracing::debug!(job_id = %job.job_id, bytes, "logs shipped"), @@ -415,7 +429,7 @@ impl Runner { Err(e) => tracing::error!(job_id = %job.job_id, error = %e, "log task panicked"), } - self.finish(&job, &result).await; + self.finish(&job, &result, oom_kills).await; if let Some(dir) = workspace_dir && let Err(e) = workspace::cleanup(&dir).await { @@ -476,11 +490,13 @@ impl Runner { Ok(()) } - async fn finish(&self, job: &JobAssignment, result: &ExecResult) { + async fn finish(&self, job: &JobAssignment, result: &ExecResult, oom_kills: Option) { let req = FinishRequest { outcome: result.outcome, exit_code: result.exit_code, message: result.message.clone(), + oom_killed: oom_kills.map(|_| true), + oom_kills, }; for attempt in 1..=FINISH_ATTEMPTS { match self.client.finish(&job.job_id, &job.job_token, &req).await { diff --git a/crates/forge-runner/src/sandbox/helper.rs b/crates/forge-runner/src/sandbox/helper.rs index 692e869..9412364 100644 --- a/crates/forge-runner/src/sandbox/helper.rs +++ b/crates/forge-runner/src/sandbox/helper.rs @@ -402,7 +402,11 @@ fn launch_and_wait(layout: &Layout, id: &str, spec: &Spec) -> Result Result<(), String> { /// Waits for the init process. On SIGTERM the container is killed. The child is then reaped, /// and `delete` removes the container's state. Returns the job's exit code. -fn wait_for_init(container: &mut Container, pid: Pid) -> Result { +fn wait_for_init( + container: &mut Container, + pid: Pid, + cgroup: Option<&Path>, +) -> Result { let mut killed = false; loop { if !killed && TERMINATE.load(Ordering::SeqCst) { @@ -487,10 +495,12 @@ fn wait_for_init(container: &mut Container, pid: Pid) -> Result std::thread::sleep(POLL), Ok(WaitStatus::Exited(_, code)) => { + report_oom(cgroup); delete_container(container); return Ok(code); } Ok(WaitStatus::Signaled(_, sig, _)) => { + report_oom(cgroup); delete_container(container); return Ok(128 + sig as i32); } @@ -505,6 +515,22 @@ fn wait_for_init(container: &mut Container, pid: Pid) -> Result) { + let Some(cgroup) = cgroup else { + return; + }; + let dir = Path::new("/sys/fs/cgroup").join(cgroup.strip_prefix("/").unwrap_or(cgroup)); + let Ok(text) = fs::read_to_string(dir.join("memory.events")) else { + return; + }; + let events = crate::oom::OomEvents::parse_memory_events(&text); + if events.any() { + eprintln!("{}", events.to_line()); + } +} + fn delete_container(container: &mut Container) { if let Err(e) = container.delete(true) { warn(format!("cannot delete container: {e}")); diff --git a/crates/forge-runner/tests/builtin.rs b/crates/forge-runner/tests/builtin.rs index 7e9a371..2f841b2 100644 --- a/crates/forge-runner/tests/builtin.rs +++ b/crates/forge-runner/tests/builtin.rs @@ -127,6 +127,7 @@ async fn run_job( workspace, logs: tx, cancel, + oom: forge_runner::oom::OomSink::default(), }) .await; let logs = collector.await.expect("log collector"); diff --git a/crates/forge-web/src/alerts.rs b/crates/forge-web/src/alerts.rs index 5ba7f0b..0cb6153 100644 --- a/crates/forge-web/src/alerts.rs +++ b/crates/forge-web/src/alerts.rs @@ -183,14 +183,18 @@ pub async fn runner_seen(state: &AppState, runner_id: &str) { } /// A job ended `Failure` or `Error`. Tells the admins once per run when it looks like the job was -/// killed, naming the runner. +/// killed, naming the runner. `oom_killed` is the runner's report that the OOM killer took a +/// process in the job's cgroup. pub async fn job_ended( state: &AppState, job: &forge_core::ci::CiJob, exit_code: Option, message: Option<&str>, + oom_killed: bool, ) { - if !alerts::is_kill_signature(exit_code, message) { + // The runner's own reading of the job cgroup comes first: a killed rustc leaves cargo to exit + // 101 with the signal only in the log. The exit code and message are the fallback. + if !oom_killed && !alerts::is_kill_signature(exit_code, message) { return; } let runner = match &job.runner_id { @@ -617,14 +621,44 @@ mod tests { heartbeat_at: None, cancel_requested: false, log_bytes: 0, + oom_kills: None, }; - job_ended(&state, &job, Some(137), None).await; + job_ended(&state, &job, Some(137), None, false).await; job.name = "second".into(); - job_ended(&state, &job, None, Some("signal: 9")).await; - job_ended(&state, &job, Some(1), None).await; + job_ended(&state, &job, None, Some("signal: 9"), false).await; + job_ended(&state, &job, Some(1), None, false).await; assert_eq!(inbox(&state, &tahinli).await.len(), 1); job.run_id = "run-2".into(); - job_ended(&state, &job, Some(137), None).await; + job_ended(&state, &job, Some(137), None, false).await; assert_eq!(inbox(&state, &tahinli).await.len(), 2); } + + #[tokio::test] + async fn an_oom_kill_the_job_survived_still_raises_the_alert() { + let dir = tempfile::tempdir().unwrap(); + let state = test_state(dir.path()).await; + let tahinli = admin(&state, "tahinli", false).await; + let job = forge_core::ci::CiJob { + id: "job-1".into(), + run_id: "run-1".into(), + name: "build".into(), + spec_json: "{}".into(), + state: forge_core::ci::JobState::Failure, + runner_id: None, + exit_code: Some(101), + message: None, + queued_at: None, + started_at: None, + finished_at: None, + heartbeat_at: None, + cancel_requested: false, + log_bytes: 0, + oom_kills: None, + }; + // cargo exits 101 when rustc is killed, so the exit code and message show nothing. + job_ended(&state, &job, Some(101), None, false).await; + assert_eq!(inbox(&state, &tahinli).await.len(), 0); + job_ended(&state, &job, Some(101), None, true).await; + assert_eq!(inbox(&state, &tahinli).await.len(), 1); + } } diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index 10fd4c6..a35534e 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -948,12 +948,24 @@ async fn finish_job( .map(|other| (other.id, other.state)) .collect(); let exit_code = request.exit_code.map(i64::from); + // The runner read the job cgroup's OOM counters. A count without the flag is believed too. + let oom_kills = match (request.oom_killed, request.oom_kills) { + (Some(false), _) => 0, + (_, Some(n)) => n.max(1), + (Some(true), None) => 1, + (None, None) => 0, + }; let run = state .store .finish_job(&job.id, outcome, exit_code, request.message.as_deref()) .await .map_err(api::internal)?; + if oom_kills > 0 + && let Err(e) = state.store.set_job_oom_kills(&job.id, oom_kills).await + { + tracing::warn!(error = %e, "ci: oom kills not stored"); + } let mut queued = false; let mut any_changed = false; for other in state @@ -980,7 +992,14 @@ async fn finish_job( } state.ci_live.bump_runners(); if matches!(outcome, JobState::Failure | JobState::Error) { - crate::alerts::job_ended(state, job, exit_code, request.message.as_deref()).await; + crate::alerts::job_ended( + state, + job, + exit_code, + request.message.as_deref(), + oom_kills > 0, + ) + .await; } if any_changed { state.ci_live.bump_run(&run.id); diff --git a/crates/forge-web/src/ci/api_tests.rs b/crates/forge-web/src/ci/api_tests.rs index 1688a21..00c9c51 100644 --- a/crates/forge-web/src/ci/api_tests.rs +++ b/crates/forge-web/src/ci/api_tests.rs @@ -848,6 +848,57 @@ fn finish_body(outcome: &str) -> Vec { json_body(&json!({ "outcome": outcome, "exit_code": 0, "message": null })) } +async fn finish_with(env: &Bare, secret: &str, body: Value) -> (String, Value) { + let assignment = claim_job(&env.router, secret).await; + let id = assignment["job_id"].as_str().unwrap().to_owned(); + let token = assignment["job_token"].as_str().unwrap(); + let sent = send( + &env.router, + "POST", + &format!("/api/v1/ci/jobs/{id}/finish"), + &[bearer(token)], + json_body(&body), + ) + .await; + assert_eq!(sent.status, 200, "{}", sent.json()); + (id, sent.json()) +} + +#[tokio::test] +async fn finish_stores_the_oom_kills_the_runner_saw() { + let env = bare(|_| {}).await; + let (_runner, secret) = runner(&env, &[]).await; + make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await; + // cargo exited 101 because its rustc was killed: nothing in the exit code or message. + let (id, _) = finish_with( + &env, + &secret, + json!({"outcome": "failure", "exit_code": 101, "message": null, + "oom_killed": true, "oom_kills": 2}), + ) + .await; + let stored = env.store.job_by_id(&id).await.unwrap().unwrap(); + assert_eq!(stored.oom_kills, Some(2)); + assert_eq!(stored.exit_code, Some(101)); +} + +#[tokio::test] +async fn an_old_runner_finish_body_without_oom_fields_still_works() { + let env = bare(|_| {}).await; + let (_runner, secret) = runner(&env, &[]).await; + make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await; + let (id, _) = finish_with( + &env, + &secret, + json!({"outcome": "failure", "exit_code": 1, "message": null}), + ) + .await; + assert_eq!( + env.store.job_by_id(&id).await.unwrap().unwrap().oom_kills, + None + ); +} + async fn two_step_run(env: &Bare) -> CiRun { make_run( env, diff --git a/crates/forge-web/src/pages/ci_job.rs b/crates/forge-web/src/pages/ci_job.rs index 7172f70..26a43d4 100644 --- a/crates/forge-web/src/pages/ci_job.rs +++ b/crates/forge-web/src/pages/ci_job.rs @@ -261,6 +261,8 @@ struct JobView { runner: String, exit_code: String, message: String, + /// The processes the OOM killer took in the job, when its runner reported any. + oom_kills: Option, started: String, started_full: String, finished: String, @@ -321,6 +323,9 @@ async fn job_body( if !job.message.is_empty() {

(job.message.as_str())

} + if let Some(kills) = job.oom_kills { +

(if matches!(lang, Lang::Tr) { "sonlandırıldı: bellek yetersiz" } else { "killed: out of memory" })

+ } if let Some((action, csrf)) = job.rerun.as_ref() {
@@ -418,6 +423,7 @@ async fn job_page(cx: &Cx) -> Result { .map(|code| code.to_string()) .unwrap_or_default(), message: job.message.clone().unwrap_or_default(), + oom_kills: job.oom_kills, started: job .started_at .as_deref() diff --git a/docs/ci.md b/docs/ci.md index d663287..27d3e67 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -93,6 +93,14 @@ How it is used: OOM-killed inside its own cgroup. Without `memory`, the limit is the larger of the runner's `limits.memory` and `limits.reserve_memory`. - It is the same for every job in a matrix. +- OOM kills are reported. When a job ends, the builtin executor reads the job cgroup's + `memory.events` before the cgroup is deleted, and the runner sends `oom_killed` and `oom_kills` + in the finish request. A job where rustc was killed still ends with exit 101 and only a + `signal: 9` line in its log, so the exit code never showed it. The job page then says "killed: + out of memory", and the admin alert for killed jobs fires. The counters are the kernel's + `oom_kill` (processes of the cgroup killed by any OOM killer, a host-wide one included, since + Linux 4.13) and `oom` (the cgroup hit its own limit). A process killed outside the job's cgroup is + not counted. The podman executor does not report this. Runners and forges that predate `memory` still work together. A runner that does not report free memory gets the oldest queued job as before, and a runner that gets a job with no `memory` field @@ -749,6 +757,9 @@ The claim response (`JobAssignment`) carries the repository, the commit, the job image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull request runs, and `memory_bytes` when the job declares `memory`. +The finish request (`outcome`, `exit_code`, `message`) may also carry `oom_killed` and `oom_kills`, +see [Memory](#memory). Both are optional and left out by an older runner. + A claim body also carries the runner's host facts and, for memory-aware admission, `free_memory_bytes` (budget minus the running jobs' reservations), `memory_budget_bytes` and `reserve_memory_bytes`. All of these are optional. Without `free_memory_bytes` the forge takes the