forge
Explore
Log in

Don't you dare go Hollow

The runner reports OOM kills from the job cgroup, shown on the job page and in alerts

Browse files at this commit

edff93be095a9cf619f5c64aaca4ddcb564a1fb3Ahmet Kaan GümüşParent: b3beedb
  • feat
    • the runner reports OOM kills from the job cgroup, shown on the job page and in alerts
Show full message
✨ feat: the runner reports OOM kills from the job cgroup, shown on the job page and in alerts

A killed rustc leaves cargo exiting 101 with the signal only in the log, so the exit code
and message checks missed it. The helper reads memory.events (oom, oom_kill) before the
cgroup is deleted, the runner sends oom_killed and oom_kills in the finish body, the forge
stores them, the job page says killed: out of memory and the killed-job alert fires on it,
with the old exit code and message matches kept as a fallback.
crates/forge-ci/src/proto.rsmodified+23 -0
@@ -238,6 +238,15 @@ pub struct FinishRequest {
238238 pub outcome: Outcome,
239239 pub exit_code: Option<i32>,
240240 pub message: Option<String>,
241+ /// True when the OOM killer killed a process in the job's cgroup, read from its
242+ /// `memory.events`. This is what shows an OOM kill that the job survived: cargo reports a
243+ /// killed rustc in the log and exits 101. Absent from an older runner, from a runner that
244+ /// cannot read the cgroup, and when nothing was killed.
245+ #[serde(default, skip_serializing_if = "Option::is_none")]
246+ pub oom_killed: Option<bool>,
247+ /// How many processes the OOM killer took in the job's cgroup (`oom_kill`).
248+ #[serde(default, skip_serializing_if = "Option::is_none")]
249+ pub oom_kills: Option<u32>,
241250 }
242251
243252 /// Final result of a job, reported by the runner.
@@ -301,14 +310,28 @@ mod tests {
301310 outcome: Outcome::Failure,
302311 exit_code: Some(2),
303312 message: None,
313+ oom_killed: None,
314+ oom_kills: None,
304315 };
305316 let json = serde_json::to_string(&req).unwrap();
317+ // An old runner's body, and a new runner that saw no OOM kill, look the same.
306318 assert_eq!(
307319 json,
308320 r#"{"outcome":"failure","exit_code":2,"message":null}"#
309321 );
310322 let back: FinishRequest = serde_json::from_str(&json).unwrap();
311323 assert_eq!(back, req);
324+ let oom = FinishRequest {
325+ oom_killed: Some(true),
326+ oom_kills: Some(2),
327+ ..req
328+ };
329+ let json = serde_json::to_string(&oom).unwrap();
330+ assert!(
331+ json.contains(r#""oom_killed":true,"oom_kills":2"#),
332+ "{json}"
333+ );
334+ assert_eq!(serde_json::from_str::<FinishRequest>(&json).unwrap(), oom);
312335 }
313336
314337 #[test]
crates/forge-core/migrations/0060_runner_memory.sqlmodified+4 -0
@@ -5,3 +5,7 @@
55 ALTER TABLE ci_runners ADD COLUMN reported_memory_budget INTEGER NULL;
66 ALTER TABLE ci_runners ADD COLUMN reported_memory_free INTEGER NULL;
77 ALTER TABLE ci_runners ADD COLUMN reported_memory_reserve INTEGER NULL;
8+
9+-- Processes the OOM killer took in a job's cgroup, as the runner read them from memory.events when
10+-- the job ended. NULL when the runner did not say or nothing was killed.
11+ALTER TABLE ci_jobs ADD COLUMN oom_kills INTEGER NULL;
crates/forge-core/src/ci.rsmodified+3 -0
@@ -526,6 +526,9 @@ pub struct CiJob {
526526 pub heartbeat_at: Option<String>,
527527 pub cancel_requested: bool,
528528 pub log_bytes: i64,
529+ /// Processes the OOM killer took in the job's cgroup, as its runner reported. `None` when the
530+ /// runner did not say (an older runner) or nothing was killed.
531+ pub oom_kills: Option<u32>,
529532 }
530533
531534 /// An artifact uploaded by a job. The file itself is stored outside the database.
crates/forge-core/src/store/ci.rsmodified+58 -1
@@ -24,7 +24,7 @@ use crate::time::{now_stamp, stamp_after, stamp_to_unix};
2424 use crate::token::{generate_token, hash_token};
2525
2626 const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, message, queued_at, \
27- started_at, finished_at, heartbeat_at, cancel_requested, log_bytes";
27+ started_at, finished_at, heartbeat_at, cancel_requested, log_bytes, oom_kills";
2828 const RUN_COLS: &str = "id, repo_id, number, trigger, git_ref, commit_oid, pull_number, actor_id, \
2929 state, config_error, created_at, finished_at";
3030 const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, \
@@ -151,6 +151,7 @@ fn map_job(row: &Row) -> Result<CiJob> {
151151 heartbeat_at: col_opt_text(row, 11)?,
152152 cancel_requested: col_bool(row, 12)?,
153153 log_bytes: col_int(row, 13)?,
154+ oom_kills: opt_u32(row, 14)?,
154155 })
155156 }
156157
@@ -1109,6 +1110,21 @@ impl Store {
11091110 .ok_or(Error::NotFound)
11101111 }
11111112
1113+ /// Records the OOM kills a runner saw in the job's cgroup. Zero is stored as nothing.
1114+ pub async fn set_job_oom_kills(&self, job_id: &str, kills: u32) -> Result<()> {
1115+ if kills == 0 {
1116+ return Ok(());
1117+ }
1118+ let conn = self.inner.conn.lock().await;
1119+ conn.execute(
1120+ "UPDATE ci_jobs SET oom_kills = ?2 WHERE id = ?1",
1121+ (job_id.to_string(), i64::from(kills)),
1122+ )
1123+ .await
1124+ .map_err(db_err)?;
1125+ Ok(())
1126+ }
1127+
11121128 /// Adds to the job's log size.
11131129 pub async fn add_log_bytes(&self, job_id: &str, n: i64) -> Result<()> {
11141130 if n < 0 {
@@ -2589,6 +2605,47 @@ mod tests {
25892605 assert_eq!(next.0.name, "small");
25902606 }
25912607
2608+ #[tokio::test]
2609+ async fn oom_kills_are_stored_on_the_job() {
2610+ let fx = fixture().await;
2611+ create(
2612+ &fx.store,
2613+ &fx.repo.id,
2614+ &fx.tahinli.id,
2615+ &[job("build", &[], &[])],
2616+ false,
2617+ )
2618+ .await;
2619+ let (claimed, _, _) = fx
2620+ .store
2621+ .claim_job(&bare_runner(&[]))
2622+ .await
2623+ .unwrap()
2624+ .unwrap();
2625+ assert_eq!(claimed.oom_kills, None);
2626+ fx.store.set_job_oom_kills(&claimed.id, 0).await.unwrap();
2627+ assert_eq!(
2628+ fx.store
2629+ .job_by_id(&claimed.id)
2630+ .await
2631+ .unwrap()
2632+ .unwrap()
2633+ .oom_kills,
2634+ None,
2635+ "zero is nothing"
2636+ );
2637+ fx.store.set_job_oom_kills(&claimed.id, 2).await.unwrap();
2638+ assert_eq!(
2639+ fx.store
2640+ .job_by_id(&claimed.id)
2641+ .await
2642+ .unwrap()
2643+ .unwrap()
2644+ .oom_kills,
2645+ Some(2)
2646+ );
2647+ }
2648+
25922649 #[tokio::test]
25932650 async fn claim_matches_labels_and_skips_disabled() {
25942651 let fx = fixture().await;
crates/forge-runner/src/executor.rsmodified+26 -5
@@ -31,6 +31,7 @@ use tokio_util::sync::CancellationToken;
3131 use crate::config::{Limits, RegistryConfig};
3232 use crate::logs::forward_lines;
3333 use crate::oci::{ImageError, ImageStore, PreparedImage, RegistryAuth};
34+use crate::oom::{OomEvents, OomSink};
3435 use crate::sandbox::helper::EXIT_SETUP_FAILED;
3536 use crate::sandbox::idmap::{IdMap, remove_tree};
3637 use crate::sandbox::{SandboxRequest, job_cgroup_path};
@@ -53,6 +54,9 @@ pub struct ExecRequest<'a> {
5354 pub logs: mpsc::Sender<Vec<u8>>,
5455 /// Cancelling this stops the job. The executor then reports `Outcome::Cancelled`.
5556 pub cancel: CancellationToken,
57+ /// Where the executor leaves OOM kills it saw in the job's cgroup. Executors that cannot see
58+ /// them leave it alone.
59+ pub oom: OomSink,
5660 }
5761
5862 /// The executor's answer. The runner adds timeouts and artifact results on top of it.
@@ -308,15 +312,25 @@ struct Supervised {
308312 status: std::io::Result<ExitStatus>,
309313 /// The sandbox helper's last `forge-sandbox: <reason>` line on stderr, when it printed one.
310314 sandbox_error: Option<String>,
315+ /// The OOM counters the helper printed, when something in the job was OOM-killed.
316+ oom: Option<OomEvents>,
311317 }
312318
313319 /// Copies stderr lines to the log and remembers the last sandbox error line.
314320 async fn tap_sandbox_errors(
315321 mut lines: mpsc::Receiver<Vec<u8>>,
316322 logs: mpsc::Sender<Vec<u8>>,
317-) -> Option<String> {
323+) -> (Option<String>, Option<OomEvents>) {
318324 let mut found = None;
325+ let mut oom = None;
319326 while let Some(chunk) = lines.recv().await {
327+ // The OOM line is for the runner, not for the job log.
328+ if chunk.starts_with(SANDBOX_PREFIX)
329+ && let Some(events) = OomEvents::from_line(&String::from_utf8_lossy(&chunk))
330+ {
331+ oom = Some(events);
332+ continue;
333+ }
320334 let is_error = chunk.starts_with(SANDBOX_PREFIX)
321335 && !chunk[SANDBOX_PREFIX.len()..].starts_with(b"warning:");
322336 if is_error {
@@ -326,7 +340,7 @@ async fn tap_sandbox_errors(
326340 break;
327341 }
328342 }
329- found
343+ (found, oom)
330344 }
331345
332346 /// Forwards the child's output, waits for it, and reports how it ended. On cancellation the
@@ -375,18 +389,19 @@ async fn supervise(
375389 reader.abort();
376390 }
377391 }
378- let sandbox_error = match tap {
392+ let (sandbox_error, oom) = match tap {
379393 Some(tap) => match tokio::time::timeout(READER_GRACE, tap).await {
380394 Ok(Ok(found)) => found,
381- _ => None,
395+ _ => (None, None),
382396 },
383- None => None,
397+ None => (None, None),
384398 };
385399
386400 Supervised {
387401 cancelled,
388402 status,
389403 sandbox_error,
404+ oom,
390405 }
391406 }
392407
@@ -586,6 +601,7 @@ impl<I: ImageSource> BuiltinExecutor<I> {
586601 workspace,
587602 logs,
588603 cancel,
604+ oom: oom_sink,
589605 } = req;
590606 if let Err(e) = validate_job_id(&job.job_id) {
591607 return error_result(e.to_string());
@@ -660,6 +676,7 @@ impl<I: ImageSource> BuiltinExecutor<I> {
660676 cancelled,
661677 status,
662678 sandbox_error,
679+ oom,
663680 } = supervise(
664681 child,
665682 logs,
@@ -674,6 +691,9 @@ impl<I: ImageSource> BuiltinExecutor<I> {
674691 }),
675692 )
676693 .await;
694+ if let Some(events) = oom {
695+ oom_sink.record(events);
696+ }
677697 if cancelled {
678698 return cancelled_result();
679699 }
@@ -920,6 +940,7 @@ mod tests {
920940 workspace: &ws,
921941 logs: tx,
922942 cancel: CancellationToken::new(),
943+ oom: OomSink::default(),
923944 })
924945 .await;
925946 assert_eq!(result.outcome, Outcome::Success, "{result:?}");
crates/forge-runner/src/lib.rsmodified+1 -0
@@ -15,6 +15,7 @@ pub mod limiter;
1515 pub mod logs;
1616 pub mod memory;
1717 pub mod oci;
18+pub mod oom;
1819 pub mod restart;
1920 pub mod runner;
2021 pub mod sandbox;
crates/forge-runner/src/oom.rsadded+171 -0
@@ -0,0 +1,171 @@
1+//! Out-of-memory kills inside a job's cgroup. The sandbox helper reads the cgroup's `memory.events`
2+//! when the job's init exits, before it deletes the cgroup, and prints one line on stderr. The
3+//! runner reads that line back and reports it when it finishes the job.
4+//!
5+//! Why the cgroup and not the exit code: when rustc is killed, cargo prints `(signal: 9, SIGKILL:
6+//! kill)` in the log and itself exits 101, so neither the job's exit code nor its message shows it.
7+//!
8+//! Kernel semantics (`Documentation/admin-guide/cgroup-v2.rst`): in `memory.events`, `oom` counts
9+//! how often the cgroup reached its limit and the OOM killer was invoked for it, and `oom_kill`
10+//! counts the processes of this cgroup that were killed by any kind of OOM killer. The victim's
11+//! cgroup is charged in `oom_kill_process`, so a victim of a host-wide OOM (global OOM killer,
12+//! nothing hit its own `memory.max`) is still counted in `oom_kill` of the cgroup it lived in, on
13+//! kernels since 4.13 that have the counter. `oom` stays 0 in that case, which is why both are
14+//! read and `oom_kill` is the one to trust. Both are hierarchical in `memory.events`, so a
15+//! process in a child cgroup counts too. A victim that was not in the job's cgroup at all (the
16+//! runner itself) is not counted, and nothing here can see it.
17+
18+use std::sync::Arc;
19+use std::sync::atomic::{AtomicU32, Ordering};
20+
21+/// The line the helper prints. It starts with the sandbox prefix, see `SANDBOX_PREFIX`.
22+pub const LINE_PREFIX: &str = "forge-sandbox: oom-events ";
23+
24+/// The `oom` and `oom_kill` counters of a job cgroup.
25+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
26+pub struct OomEvents {
27+ pub oom: u64,
28+ pub oom_kill: u64,
29+}
30+
31+impl OomEvents {
32+ /// Reads the counters from the text of a `memory.events` file. Missing keys count as 0.
33+ pub fn parse_memory_events(text: &str) -> Self {
34+ let mut events = Self::default();
35+ for line in text.lines() {
36+ let mut parts = line.split_whitespace();
37+ let (Some(key), Some(value)) = (parts.next(), parts.next()) else {
38+ continue;
39+ };
40+ let value = value.parse().unwrap_or(0);
41+ match key {
42+ "oom" => events.oom = value,
43+ "oom_kill" => events.oom_kill = value,
44+ _ => {}
45+ }
46+ }
47+ events
48+ }
49+
50+ /// True when something in the job was OOM-killed or the cgroup hit its limit.
51+ pub fn any(&self) -> bool {
52+ self.oom > 0 || self.oom_kill > 0
53+ }
54+
55+ /// How many kills to report: `oom_kill`, or `oom` when only that one moved.
56+ pub fn kills(&self) -> u32 {
57+ u32::try_from(self.oom_kill.max(self.oom)).unwrap_or(u32::MAX)
58+ }
59+
60+ /// The stderr line for the runner, without a newline.
61+ pub fn to_line(&self) -> String {
62+ format!("{LINE_PREFIX}oom={} oom_kill={}", self.oom, self.oom_kill)
63+ }
64+
65+ /// Reads a line written by [`OomEvents::to_line`].
66+ pub fn from_line(line: &str) -> Option<Self> {
67+ let rest = line.trim_end().strip_prefix(LINE_PREFIX)?;
68+ let mut events = Self::default();
69+ for pair in rest.split_whitespace() {
70+ let (key, value) = pair.split_once('=')?;
71+ let value = value.parse().ok()?;
72+ match key {
73+ "oom" => events.oom = value,
74+ "oom_kill" => events.oom_kill = value,
75+ _ => {}
76+ }
77+ }
78+ Some(events)
79+ }
80+}
81+
82+/// Where an executor leaves the OOM kills it saw for a job. Cheap to clone and share.
83+#[derive(Clone, Debug, Default)]
84+pub struct OomSink(Arc<AtomicU32>);
85+
86+impl OomSink {
87+ pub fn record(&self, events: OomEvents) {
88+ if events.any() {
89+ self.0.store(events.kills().max(1), Ordering::SeqCst);
90+ }
91+ }
92+
93+ /// The reported kills, or `None` when nothing was killed or the executor cannot tell.
94+ pub fn kills(&self) -> Option<u32> {
95+ match self.0.load(Ordering::SeqCst) {
96+ 0 => None,
97+ n => Some(n),
98+ }
99+ }
100+}
101+
102+#[cfg(test)]
103+mod tests {
104+ use super::*;
105+
106+ const EVENTS: &str = "low 0\nhigh 0\nmax 12\noom 2\noom_kill 3\noom_group_kill 0\n";
107+
108+ #[test]
109+ fn memory_events_are_parsed() {
110+ let events = OomEvents::parse_memory_events(EVENTS);
111+ assert_eq!(
112+ events,
113+ OomEvents {
114+ oom: 2,
115+ oom_kill: 3
116+ }
117+ );
118+ assert!(events.any());
119+ assert_eq!(events.kills(), 3);
120+ }
121+
122+ #[test]
123+ fn a_clean_cgroup_reports_nothing() {
124+ let events = OomEvents::parse_memory_events("low 0\nhigh 0\nmax 4\noom 0\noom_kill 0\n");
125+ assert!(!events.any());
126+ assert_eq!(events.kills(), 0);
127+ let sink = OomSink::default();
128+ sink.record(events);
129+ assert_eq!(sink.kills(), None);
130+ // Older kernels have no counters at all.
131+ assert!(!OomEvents::parse_memory_events("low 0\nmax 1\n").any());
132+ assert!(!OomEvents::parse_memory_events("").any());
133+ }
134+
135+ #[test]
136+ fn a_host_wide_oom_shows_in_oom_kill_only() {
137+ // The job's own limit was never reached, but its rustc was the global OOM victim.
138+ let events = OomEvents::parse_memory_events("max 0\noom 0\noom_kill 1\n");
139+ assert!(events.any());
140+ assert_eq!(events.kills(), 1);
141+ }
142+
143+ #[test]
144+ fn the_stderr_line_round_trips() {
145+ let events = OomEvents {
146+ oom: 1,
147+ oom_kill: 2,
148+ };
149+ assert_eq!(
150+ events.to_line(),
151+ "forge-sandbox: oom-events oom=1 oom_kill=2"
152+ );
153+ assert_eq!(OomEvents::from_line(&events.to_line()), Some(events));
154+ assert_eq!(OomEvents::from_line("forge-sandbox: setup failed"), None);
155+ assert_eq!(
156+ OomEvents::from_line("forge-sandbox: oom-events oom=x"),
157+ None
158+ );
159+ }
160+
161+ #[test]
162+ fn the_sink_keeps_the_count() {
163+ let sink = OomSink::default();
164+ let shared = sink.clone();
165+ shared.record(OomEvents {
166+ oom: 0,
167+ oom_kill: 2,
168+ });
169+ assert_eq!(sink.kills(), Some(2));
170+ }
171+}
crates/forge-runner/src/runner.rsmodified+18 -2
@@ -20,6 +20,7 @@ use crate::executor::{ExecRequest, ExecResult, Executor};
2020 use crate::limiter::Limiter;
2121 use crate::logs::{self, PumpConfig};
2222 use crate::memory::MemoryGate;
23+use crate::oom::OomSink;
2324 use crate::restart::{self, RestartState, Step};
2425 use crate::update::{self, Installed, UpdateState};
2526 use crate::workspace;
@@ -342,6 +343,7 @@ impl Runner {
342343 };
343344
344345 let mut workspace_dir = None;
346+ let oom = OomSink::default();
345347 let prepared = workspace::prepare(&self.config.work_dir, &job, &self.config.url).await;
346348 let mut result = match prepared {
347349 Ok(dir) => {
@@ -357,6 +359,7 @@ impl Runner {
357359 workspace: &dir,
358360 logs: tx.clone(),
359361 cancel: job_cancel.clone(),
362+ oom: oom.clone(),
360363 })
361364 .await;
362365 workspace_dir = Some(dir);
@@ -408,6 +411,17 @@ impl Runner {
408411 if let Some(message) = &result.message {
409412 send_line(&tx, format!("runner: {message}")).await;
410413 }
414+ let oom_kills = oom.kills();
415+ if let Some(kills) = oom_kills {
416+ send_line(
417+ &tx,
418+ format!(
419+ "runner: the out of memory killer killed {kills} process(es) in this job; \
420+ the job's memory is limited to its `memory` plus a little slack, see docs/ci.md"
421+ ),
422+ )
423+ .await;
424+ }
411425 drop(tx);
412426 match pump.await {
413427 Ok(Ok(bytes)) => tracing::debug!(job_id = %job.job_id, bytes, "logs shipped"),
@@ -415,7 +429,7 @@ impl Runner {
415429 Err(e) => tracing::error!(job_id = %job.job_id, error = %e, "log task panicked"),
416430 }
417431
418- self.finish(&job, &result).await;
432+ self.finish(&job, &result, oom_kills).await;
419433 if let Some(dir) = workspace_dir
420434 && let Err(e) = workspace::cleanup(&dir).await
421435 {
@@ -476,11 +490,13 @@ impl Runner {
476490 Ok(())
477491 }
478492
479- async fn finish(&self, job: &JobAssignment, result: &ExecResult) {
493+ async fn finish(&self, job: &JobAssignment, result: &ExecResult, oom_kills: Option<u32>) {
480494 let req = FinishRequest {
481495 outcome: result.outcome,
482496 exit_code: result.exit_code,
483497 message: result.message.clone(),
498+ oom_killed: oom_kills.map(|_| true),
499+ oom_kills,
484500 };
485501 for attempt in 1..=FINISH_ATTEMPTS {
486502 match self.client.finish(&job.job_id, &job.job_token, &req).await {
crates/forge-runner/src/sandbox/helper.rsmodified+28 -2
@@ -402,7 +402,11 @@ fn launch_and_wait(layout: &Layout, id: &str, spec: &Spec) -> Result<i32, Sandbo
402402 return Err(e);
403403 }
404404 };
405- wait_for_init(&mut container, pid)
405+ let cgroup = spec
406+ .linux()
407+ .as_ref()
408+ .and_then(|linux| linux.cgroups_path().clone());
409+ wait_for_init(&mut container, pid, cgroup.as_deref())
406410 }
407411
408412 /// Writes `bundle/config.json` (0600). It holds the job env and secrets, so it is removed right
@@ -475,7 +479,11 @@ fn kill_container(container: &mut Container) -> Result<(), String> {
475479
476480 /// Waits for the init process. On SIGTERM the container is killed. The child is then reaped,
477481 /// and `delete` removes the container's state. Returns the job's exit code.
478-fn wait_for_init(container: &mut Container, pid: Pid) -> Result<i32, SandboxError> {
482+fn wait_for_init(
483+ container: &mut Container,
484+ pid: Pid,
485+ cgroup: Option<&Path>,
486+) -> Result<i32, SandboxError> {
479487 let mut killed = false;
480488 loop {
481489 if !killed && TERMINATE.load(Ordering::SeqCst) {
@@ -487,10 +495,12 @@ fn wait_for_init(container: &mut Container, pid: Pid) -> Result<i32, SandboxErro
487495 match waitpid(pid, Some(WaitPidFlag::WNOHANG)) {
488496 Ok(WaitStatus::StillAlive) => std::thread::sleep(POLL),
489497 Ok(WaitStatus::Exited(_, code)) => {
498+ report_oom(cgroup);
490499 delete_container(container);
491500 return Ok(code);
492501 }
493502 Ok(WaitStatus::Signaled(_, sig, _)) => {
503+ report_oom(cgroup);
494504 delete_container(container);
495505 return Ok(128 + sig as i32);
496506 }
@@ -505,6 +515,22 @@ fn wait_for_init(container: &mut Container, pid: Pid) -> Result<i32, SandboxErro
505515 }
506516 }
507517
518+/// Prints the job cgroup's OOM counters for the runner when something was OOM-killed. It runs
519+/// after the init exited and before the cgroup is deleted, the only time the file still exists.
520+fn report_oom(cgroup: Option<&Path>) {
521+ let Some(cgroup) = cgroup else {
522+ return;
523+ };
524+ let dir = Path::new("/sys/fs/cgroup").join(cgroup.strip_prefix("/").unwrap_or(cgroup));
525+ let Ok(text) = fs::read_to_string(dir.join("memory.events")) else {
526+ return;
527+ };
528+ let events = crate::oom::OomEvents::parse_memory_events(&text);
529+ if events.any() {
530+ eprintln!("{}", events.to_line());
531+ }
532+}
533+
508534 fn delete_container(container: &mut Container) {
509535 if let Err(e) = container.delete(true) {
510536 warn(format!("cannot delete container: {e}"));
crates/forge-runner/tests/builtin.rsmodified+1 -0
@@ -127,6 +127,7 @@ async fn run_job(
127127 workspace,
128128 logs: tx,
129129 cancel,
130+ oom: forge_runner::oom::OomSink::default(),
130131 })
131132 .await;
132133 let logs = collector.await.expect("log collector");
crates/forge-web/src/alerts.rsmodified+40 -6
@@ -183,14 +183,18 @@ pub async fn runner_seen(state: &AppState, runner_id: &str) {
183183 }
184184
185185 /// A job ended `Failure` or `Error`. Tells the admins once per run when it looks like the job was
186-/// killed, naming the runner.
186+/// killed, naming the runner. `oom_killed` is the runner's report that the OOM killer took a
187+/// process in the job's cgroup.
187188 pub async fn job_ended(
188189 state: &AppState,
189190 job: &forge_core::ci::CiJob,
190191 exit_code: Option<i64>,
191192 message: Option<&str>,
193+ oom_killed: bool,
192194 ) {
193- if !alerts::is_kill_signature(exit_code, message) {
195+ // The runner's own reading of the job cgroup comes first: a killed rustc leaves cargo to exit
196+ // 101 with the signal only in the log. The exit code and message are the fallback.
197+ if !oom_killed && !alerts::is_kill_signature(exit_code, message) {
194198 return;
195199 }
196200 let runner = match &job.runner_id {
@@ -617,14 +621,44 @@ mod tests {
617621 heartbeat_at: None,
618622 cancel_requested: false,
619623 log_bytes: 0,
624+ oom_kills: None,
620625 };
621- job_ended(&state, &job, Some(137), None).await;
626+ job_ended(&state, &job, Some(137), None, false).await;
622627 job.name = "second".into();
623- job_ended(&state, &job, None, Some("signal: 9")).await;
624- job_ended(&state, &job, Some(1), None).await;
628+ job_ended(&state, &job, None, Some("signal: 9"), false).await;
629+ job_ended(&state, &job, Some(1), None, false).await;
625630 assert_eq!(inbox(&state, &tahinli).await.len(), 1);
626631 job.run_id = "run-2".into();
627- job_ended(&state, &job, Some(137), None).await;
632+ job_ended(&state, &job, Some(137), None, false).await;
628633 assert_eq!(inbox(&state, &tahinli).await.len(), 2);
629634 }
635+
636+ #[tokio::test]
637+ async fn an_oom_kill_the_job_survived_still_raises_the_alert() {
638+ let dir = tempfile::tempdir().unwrap();
639+ let state = test_state(dir.path()).await;
640+ let tahinli = admin(&state, "tahinli", false).await;
641+ let job = forge_core::ci::CiJob {
642+ id: "job-1".into(),
643+ run_id: "run-1".into(),
644+ name: "build".into(),
645+ spec_json: "{}".into(),
646+ state: forge_core::ci::JobState::Failure,
647+ runner_id: None,
648+ exit_code: Some(101),
649+ message: None,
650+ queued_at: None,
651+ started_at: None,
652+ finished_at: None,
653+ heartbeat_at: None,
654+ cancel_requested: false,
655+ log_bytes: 0,
656+ oom_kills: None,
657+ };
658+ // cargo exits 101 when rustc is killed, so the exit code and message show nothing.
659+ job_ended(&state, &job, Some(101), None, false).await;
660+ assert_eq!(inbox(&state, &tahinli).await.len(), 0);
661+ job_ended(&state, &job, Some(101), None, true).await;
662+ assert_eq!(inbox(&state, &tahinli).await.len(), 1);
663+ }
630664 }
crates/forge-web/src/ci/api.rsmodified+20 -1
@@ -948,12 +948,24 @@ async fn finish_job(
948948 .map(|other| (other.id, other.state))
949949 .collect();
950950 let exit_code = request.exit_code.map(i64::from);
951+ // The runner read the job cgroup's OOM counters. A count without the flag is believed too.
952+ let oom_kills = match (request.oom_killed, request.oom_kills) {
953+ (Some(false), _) => 0,
954+ (_, Some(n)) => n.max(1),
955+ (Some(true), None) => 1,
956+ (None, None) => 0,
957+ };
951958 let run = state
952959 .store
953960 .finish_job(&job.id, outcome, exit_code, request.message.as_deref())
954961 .await
955962 .map_err(api::internal)?;
956963
964+ if oom_kills > 0
965+ && let Err(e) = state.store.set_job_oom_kills(&job.id, oom_kills).await
966+ {
967+ tracing::warn!(error = %e, "ci: oom kills not stored");
968+ }
957969 let mut queued = false;
958970 let mut any_changed = false;
959971 for other in state
@@ -980,7 +992,14 @@ async fn finish_job(
980992 }
981993 state.ci_live.bump_runners();
982994 if matches!(outcome, JobState::Failure | JobState::Error) {
983- crate::alerts::job_ended(state, job, exit_code, request.message.as_deref()).await;
995+ crate::alerts::job_ended(
996+ state,
997+ job,
998+ exit_code,
999+ request.message.as_deref(),
1000+ oom_kills > 0,
1001+ )
1002+ .await;
9841003 }
9851004 if any_changed {
9861005 state.ci_live.bump_run(&run.id);
crates/forge-web/src/ci/api_tests.rsmodified+51 -0
@@ -848,6 +848,57 @@ fn finish_body(outcome: &str) -> Vec<u8> {
848848 json_body(&json!({ "outcome": outcome, "exit_code": 0, "message": null }))
849849 }
850850
851+async fn finish_with(env: &Bare, secret: &str, body: Value) -> (String, Value) {
852+ let assignment = claim_job(&env.router, secret).await;
853+ let id = assignment["job_id"].as_str().unwrap().to_owned();
854+ let token = assignment["job_token"].as_str().unwrap();
855+ let sent = send(
856+ &env.router,
857+ "POST",
858+ &format!("/api/v1/ci/jobs/{id}/finish"),
859+ &[bearer(token)],
860+ json_body(&body),
861+ )
862+ .await;
863+ assert_eq!(sent.status, 200, "{}", sent.json());
864+ (id, sent.json())
865+}
866+
867+#[tokio::test]
868+async fn finish_stores_the_oom_kills_the_runner_saw() {
869+ let env = bare(|_| {}).await;
870+ let (_runner, secret) = runner(&env, &[]).await;
871+ make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await;
872+ // cargo exited 101 because its rustc was killed: nothing in the exit code or message.
873+ let (id, _) = finish_with(
874+ &env,
875+ &secret,
876+ json!({"outcome": "failure", "exit_code": 101, "message": null,
877+ "oom_killed": true, "oom_kills": 2}),
878+ )
879+ .await;
880+ let stored = env.store.job_by_id(&id).await.unwrap().unwrap();
881+ assert_eq!(stored.oom_kills, Some(2));
882+ assert_eq!(stored.exit_code, Some(101));
883+}
884+
885+#[tokio::test]
886+async fn an_old_runner_finish_body_without_oom_fields_still_works() {
887+ let env = bare(|_| {}).await;
888+ let (_runner, secret) = runner(&env, &[]).await;
889+ make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await;
890+ let (id, _) = finish_with(
891+ &env,
892+ &secret,
893+ json!({"outcome": "failure", "exit_code": 1, "message": null}),
894+ )
895+ .await;
896+ assert_eq!(
897+ env.store.job_by_id(&id).await.unwrap().unwrap().oom_kills,
898+ None
899+ );
900+}
901+
851902 async fn two_step_run(env: &Bare) -> CiRun {
852903 make_run(
853904 env,
crates/forge-web/src/pages/ci_job.rsmodified+6 -0
@@ -261,6 +261,8 @@ struct JobView {
261261 runner: String,
262262 exit_code: String,
263263 message: String,
264+ /// The processes the OOM killer took in the job, when its runner reported any.
265+ oom_kills: Option<u32>,
264266 started: String,
265267 started_full: String,
266268 finished: String,
@@ -321,6 +323,9 @@ async fn job_body(
321323 if !job.message.is_empty() {
322324 <p>(job.message.as_str())</p>
323325 }
326+ if let Some(kills) = job.oom_kills {
327+ <p class="alert" title=(format!("oom_kill {kills}"))>(if matches!(lang, Lang::Tr) { "sonlandırıldı: bellek yetersiz" } else { "killed: out of memory" })</p>
328+ }
324329 if let Some((action, csrf)) = job.rerun.as_ref() {
325330 <div class="ci-actions">
326331 <form method="post" action=(action.as_str()) class="inline-form">
@@ -418,6 +423,7 @@ async fn job_page(cx: &Cx) -> Result<impl View> {
418423 .map(|code| code.to_string())
419424 .unwrap_or_default(),
420425 message: job.message.clone().unwrap_or_default(),
426+ oom_kills: job.oom_kills,
421427 started: job
422428 .started_at
423429 .as_deref()
docs/ci.mdmodified+11 -0
@@ -93,6 +93,14 @@ How it is used:
9393 OOM-killed inside its own cgroup. Without `memory`, the limit is the larger of the runner's
9494 `limits.memory` and `limits.reserve_memory`.
9595 - It is the same for every job in a matrix.
96+- OOM kills are reported. When a job ends, the builtin executor reads the job cgroup's
97+ `memory.events` before the cgroup is deleted, and the runner sends `oom_killed` and `oom_kills`
98+ in the finish request. A job where rustc was killed still ends with exit 101 and only a
99+ `signal: 9` line in its log, so the exit code never showed it. The job page then says "killed:
100+ out of memory", and the admin alert for killed jobs fires. The counters are the kernel's
101+ `oom_kill` (processes of the cgroup killed by any OOM killer, a host-wide one included, since
102+ Linux 4.13) and `oom` (the cgroup hit its own limit). A process killed outside the job's cgroup is
103+ not counted. The podman executor does not report this.
96104
97105 Runners and forges that predate `memory` still work together. A runner that does not report free
98106 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
749757 image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull
750758 request runs, and `memory_bytes` when the job declares `memory`.
751759
760+The finish request (`outcome`, `exit_code`, `message`) may also carry `oom_killed` and `oom_kills`,
761+see [Memory](#memory). Both are optional and left out by an older runner.
762+
752763 A claim body also carries the runner's host facts and, for memory-aware admission,
753764 `free_memory_bytes` (budget minus the running jobs' reservations), `memory_budget_bytes` and
754765 `reserve_memory_bytes`. All of these are optional. Without `free_memory_bytes` the forge takes the