1use regex::Regex;
19
20const EXIT_REASON_MARKERS: [(&str, &str); 5] = [
22 (
23 "memory-exhaustion (v8-heap-limit)",
24 r"(?i)FATAL ERROR:[^\r\n]*(?:Reached heap limit|JavaScript heap out of memory)",
25 ),
26 (
27 "memory-exhaustion (v8-heap-limit)",
28 r"(?i)JavaScript heap out of memory",
29 ),
30 (
31 "memory-exhaustion (kernel-oom-killer)",
32 r"(?i)Out of memory: Kill(?:ed)? process|oom-kill(?:er)?[: ]|Killed process \d+",
33 ),
34 (
35 "memory-exhaustion (go-runtime)",
36 r"(?i)fatal error: runtime: out of memory",
37 ),
38 (
39 "memory-exhaustion (allocation-failure)",
40 r"(?i)std::bad_alloc|Cannot allocate memory|memory allocation of \d+ bytes failed|Allocation failed - process out of memory|Array buffer allocation failed",
41 ),
42];
43
44pub const SIGNAL_NAMES: [(i32, &str); 10] = [
51 (1, "SIGHUP"),
52 (2, "SIGINT"),
53 (3, "SIGQUIT"),
54 (4, "SIGILL"),
55 (6, "SIGABRT"),
56 (8, "SIGFPE"),
57 (9, "SIGKILL"),
58 (11, "SIGSEGV"),
59 (13, "SIGPIPE"),
60 (15, "SIGTERM"),
61];
62
63const MEMORY_EXHAUSTION_PREFIX: &str = "memory-exhaustion";
66
67const MAX_MARKER_LINE_LENGTH: usize = 300;
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct ExitReasonMarker {
74 pub reason: String,
75 pub line: String,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct MemoryExhaustion {
81 pub memory_exhausted: bool,
82 pub memory_exhausted_reason: String,
83}
84
85fn extract_line_at(text: &str, index: usize) -> String {
87 let start = text[..index].rfind('\n').map(|i| i + 1).unwrap_or(0);
88 let end = text[index..]
89 .find('\n')
90 .map(|i| index + i)
91 .unwrap_or(text.len());
92 let line = text[start..end].trim();
93 if line.chars().count() <= MAX_MARKER_LINE_LENGTH {
94 return line.to_string();
95 }
96 let truncated: String = line.chars().take(MAX_MARKER_LINE_LENGTH).collect();
97 format!("{}...", truncated)
98}
99
100pub fn find_exit_reason_marker(
102 text: Option<&str>,
103 accept: impl Fn(&str) -> bool,
104) -> Option<ExitReasonMarker> {
105 let text = text?;
106 if text.is_empty() {
107 return None;
108 }
109 for (reason, pattern) in EXIT_REASON_MARKERS {
110 if !accept(reason) {
111 continue;
112 }
113 if let Ok(re) = Regex::new(pattern) {
114 if let Some(found) = re.find(text) {
115 return Some(ExitReasonMarker {
116 reason: reason.to_string(),
117 line: extract_line_at(text, found.start()),
118 });
119 }
120 }
121 }
122 None
123}
124
125pub fn detect_exit_reason(text: Option<&str>) -> Option<String> {
127 find_exit_reason_marker(text, |_| true).map(|marker| marker.reason)
128}
129
130pub fn detect_memory_marker(text: Option<&str>) -> Option<ExitReasonMarker> {
132 find_exit_reason_marker(text, |reason| reason.starts_with(MEMORY_EXHAUSTION_PREFIX))
133}
134
135pub fn resolve_memory_exhaustion(
141 exit_code: Option<i32>,
142 log_tail: Option<&str>,
143 oom_killed: Option<bool>,
144) -> Option<MemoryExhaustion> {
145 match exit_code {
146 Some(code) if code != 0 => {}
147 _ => return None,
148 }
149 if let Some(marker) = detect_memory_marker(log_tail) {
150 return Some(MemoryExhaustion {
151 memory_exhausted: true,
152 memory_exhausted_reason: marker.line,
153 });
154 }
155 if oom_killed == Some(true) {
156 return Some(MemoryExhaustion {
157 memory_exhausted: true,
158 memory_exhausted_reason: "Docker reported State.OOMKilled=true".to_string(),
159 });
160 }
161 None
162}
163
164pub const UNKNOWN_EXIT_CODE: &str = "unknown";
166
167#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct ExitCodeDescription {
172 pub code: Option<i32>,
173 pub signal: Option<String>,
174 pub text: String,
175}
176
177pub fn describe_exit_code(exit_code: Option<i32>) -> ExitCodeDescription {
183 let code = match exit_code {
184 Some(code) => code,
185 None => {
186 return ExitCodeDescription {
187 code: None,
188 signal: None,
189 text: UNKNOWN_EXIT_CODE.to_string(),
190 }
191 }
192 };
193 let signal = signal_name_for_exit_code(Some(code));
194 let text = match &signal {
195 Some(name) => format!("{} ({} - 128+{})", code, name, code - 128),
196 None => code.to_string(),
197 };
198 ExitCodeDescription {
199 code: Some(code),
200 signal,
201 text,
202 }
203}
204
205pub fn describe_exit_code_str(value: &str) -> ExitCodeDescription {
207 describe_exit_code(value.trim().parse::<i32>().ok())
208}
209
210pub fn signal_name_for_exit_code(exit_code: Option<i32>) -> Option<String> {
212 let code = exit_code?;
213 if code <= 128 || code > 128 + 64 {
214 return None;
215 }
216 SIGNAL_NAMES
217 .iter()
218 .find(|(signal, _)| *signal == code - 128)
219 .map(|(_, name)| name.to_string())
220}
221
222pub fn resolve_exit_reason(
227 exit_code: Option<i32>,
228 log_tail: Option<&str>,
229 oom_killed: Option<bool>,
230) -> Option<String> {
231 if let Some(reason) = detect_exit_reason(log_tail) {
232 return Some(reason);
233 }
234
235 if oom_killed == Some(true) {
236 return Some("memory-exhaustion (cgroup-oom-killer)".to_string());
237 }
238
239 signal_name_for_exit_code(exit_code).map(|name| format!("signal ({})", name))
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 #[test]
247 fn detects_v8_heap_limit_from_the_incident_log() {
248 let tail =
249 "FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory";
250 assert_eq!(
251 detect_exit_reason(Some(tail)),
252 Some("memory-exhaustion (v8-heap-limit)".to_string())
253 );
254 }
255
256 #[test]
257 fn detects_kernel_oom_killer() {
258 assert_eq!(
259 detect_exit_reason(Some("Out of memory: Killed process 1234 (bun)")),
260 Some("memory-exhaustion (kernel-oom-killer)".to_string())
261 );
262 }
263
264 #[test]
265 fn detects_other_runtimes_reporting_their_own_exhaustion() {
266 assert_eq!(
267 detect_exit_reason(Some("fatal error: runtime: out of memory")),
268 Some("memory-exhaustion (go-runtime)".to_string())
269 );
270 assert_eq!(
271 detect_exit_reason(Some("Array buffer allocation failed")),
272 Some("memory-exhaustion (allocation-failure)".to_string())
273 );
274 }
275
276 #[test]
277 fn returns_none_for_ordinary_output() {
278 assert_eq!(detect_exit_reason(Some("all tests passed")), None);
279 assert_eq!(detect_exit_reason(None), None);
280 }
281
282 #[test]
283 fn maps_signal_exit_codes() {
284 assert_eq!(signal_name_for_exit_code(Some(137)), Some("SIGKILL".into()));
285 assert_eq!(signal_name_for_exit_code(Some(139)), Some("SIGSEGV".into()));
286 assert_eq!(signal_name_for_exit_code(Some(0)), None);
287 assert_eq!(signal_name_for_exit_code(Some(1)), None);
288 assert_eq!(signal_name_for_exit_code(None), None);
289 }
290
291 #[test]
292 fn log_marker_wins_over_signal_and_cgroup_flag() {
293 let tail =
294 "FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory";
295 assert_eq!(
296 resolve_exit_reason(Some(139), Some(tail), Some(false)),
297 Some("memory-exhaustion (v8-heap-limit)".to_string())
298 );
299 }
300
301 #[test]
302 fn memory_marker_returns_the_whole_matched_line() {
303 let tail = "building...\nFATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory\n----- Native stack trace -----\n";
304 let marker = detect_memory_marker(Some(tail)).expect("marker");
305 assert_eq!(marker.reason, "memory-exhaustion (v8-heap-limit)");
306 assert_eq!(
307 marker.line,
308 "FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory"
309 );
310 }
311
312 #[test]
313 fn memory_marker_line_is_length_bounded() {
314 let tail = format!(
315 "{}JavaScript heap out of memory{}",
316 "x".repeat(400),
317 "y".repeat(400)
318 );
319 let marker = detect_memory_marker(Some(&tail)).expect("marker");
320 assert!(marker.line.chars().count() <= MAX_MARKER_LINE_LENGTH + 3);
321 assert!(marker.line.ends_with("..."));
322 }
323
324 #[test]
325 fn memory_exhaustion_explains_only_abnormal_exits() {
326 let tail =
327 "FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory";
328 let observed =
329 resolve_memory_exhaustion(Some(139), Some(tail), Some(false)).expect("observed");
330 assert!(observed.memory_exhausted);
331 assert_eq!(observed.memory_exhausted_reason, tail);
332 assert_eq!(
334 resolve_memory_exhaustion(Some(0), Some(tail), Some(false)),
335 None
336 );
337 assert_eq!(resolve_memory_exhaustion(None, Some(tail), None), None);
338 }
339
340 #[test]
341 fn memory_exhaustion_falls_back_to_the_container_flag() {
342 let observed =
343 resolve_memory_exhaustion(Some(137), Some("no marker"), Some(true)).expect("observed");
344 assert_eq!(
345 observed.memory_exhausted_reason,
346 "Docker reported State.OOMKilled=true"
347 );
348 assert_eq!(
349 resolve_memory_exhaustion(Some(1), Some("no marker"), Some(false)),
350 None
351 );
352 }
353
354 #[test]
355 fn falls_back_to_cgroup_observation_then_signal() {
356 assert_eq!(
357 resolve_exit_reason(Some(137), None, Some(true)),
358 Some("memory-exhaustion (cgroup-oom-killer)".to_string())
359 );
360 assert_eq!(
361 resolve_exit_reason(Some(139), Some("no marker here"), Some(false)),
362 Some("signal (SIGSEGV)".to_string())
363 );
364 assert_eq!(resolve_exit_reason(Some(0), Some("fine"), None), None);
365 }
366}