agentmux_srv_core/backend/container/
oom.rs1use futures_util::StreamExt as _;
13use std::sync::Arc;
14
15use super::ContainerManager;
16
17const READ_COUNTER: &str = "cat /sys/fs/cgroup/memory.events 2>/dev/null || cat /sys/fs/cgroup/memory/memory.oom_control 2>/dev/null";
19
20const READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
22
23pub fn parse_oom_kill(text: &str) -> Option<u64> {
25 text.lines().find_map(|line| {
26 let mut parts = line.split_whitespace();
27 (parts.next()? == "oom_kill").then(|| parts.next()?.parse().ok()).flatten()
28 })
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct OomEvent {
34 pub memory_mb: Option<u64>,
36}
37
38impl ContainerManager {
39 pub async fn oom_kill_count(&self, container_name: &str) -> Option<u64> {
42 let read = async {
43 let cmd = ["sh".to_string(), "-c".to_string(), READ_COUNTER.to_string()];
44 let session = self.exec(container_name, &cmd, None, &[], false).await.ok()?;
45 let mut text = String::new();
46 let mut output = session.output;
47 while let Some(Ok(frame)) = output.next().await {
48 text.push_str(&frame.to_string());
49 }
50 parse_oom_kill(&text)
51 };
52 tokio::time::timeout(READ_TIMEOUT, read).await.ok().flatten()
53 }
54
55 pub async fn oom_since(&self, container_name: &str, before: Option<u64>) -> Option<OomEvent> {
57 let before = before?;
58 if self.oom_kill_count(container_name).await? <= before {
59 return None;
60 }
61 let limit = self.inner.docker.inspect_container(container_name, None).await.ok().and_then(|d| d.host_config).and_then(|h| h.memory);
62 Some(OomEvent { memory_mb: limit.filter(|bytes| *bytes > 0).map(|bytes| bytes as u64 / (1024 * 1024)) })
63 }
64}
65
66pub fn explain_failure(failure: &mut crate::agents::failure::AgentFailure, event: &OomEvent) {
68 if failure.code != crate::agents::failure::FailureClass::Killed {
69 return;
70 }
71 failure.title = "Ran out of memory".to_string();
72 failure.detail = match event.memory_mb {
73 Some(mb) => format!("The container's memory limit ({}) was exceeded, so the kernel stopped a process in it. Raise the limit in the agent's container settings, or reduce what runs at once.", memory_text(mb)),
74 None => "The container ran out of memory, so the kernel stopped a process in it. Docker's own memory may be too small: raise it in Docker Desktop's resource settings, or reduce what runs at once.".to_string(),
75 };
76}
77
78pub fn memory_text(mb: u64) -> String {
80 if mb < 1024 {
81 return format!("{mb} MB");
82 }
83 let gb = mb as f64 / 1024.0;
84 if (gb - gb.round()).abs() < 0.05 { format!("{} GB", gb.round() as u64) } else { format!("{gb:.1} GB") }
85}
86
87pub fn note_in_pane(
89 event: &OomEvent,
90 block_id: &str,
91 broker: &Option<Arc<crate::backend::mps::Broker>>,
92 filestore: &Option<Arc<crate::backend::storage::filestore::FileStore>>,
93 mstore: &Option<Arc<crate::backend::storage::store::Store>>,
94) {
95 let (Some(broker), Some(filestore), Some(mstore)) = (broker, filestore, mstore) else { return };
96 let meta = |key: &str, default: &str| match mstore.get::<crate::backend::obj::Block>(block_id) {
97 Ok(Some(block)) => crate::backend::obj::meta_get_string(&block.meta, key, default),
98 _ => default.to_string(),
99 };
100 let (provider, agent_id, agent_name) = (meta("agentProvider", "claude"), meta("agentId", ""), meta("agentName", ""));
101 let frame = crate::backend::cli_notice::container_limit_frame(
102 &provider,
103 block_id,
104 (&agent_id, &agent_name),
105 "oom",
106 event.memory_mb,
107 None,
108 None,
109 None,
110 );
111 crate::backend::cli_notice::append_to_pane(broker, filestore, mstore, block_id, &frame);
112 tracing::warn!(block_id, memory_mb = ?event.memory_mb, "a process in the container was killed for memory");
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118
119 #[test]
120 fn the_counter_is_read_from_either_cgroup_version() {
121 let v2 = "low 0\nhigh 0\nmax 12\noom 3\noom_kill 2\noom_group_kill 0\n";
122 assert_eq!(parse_oom_kill(v2), Some(2));
123 let v1 = "oom_kill_disable 0\nunder_oom 0\noom_kill 5\n";
124 assert_eq!(parse_oom_kill(v1), Some(5));
125 assert_eq!(parse_oom_kill("oom_kill_disable 0\nunder_oom 0\n"), None, "an old kernel has no counter");
126 assert_eq!(parse_oom_kill(""), None);
127 }
128
129 #[test]
130 fn a_killed_turn_names_the_limit_and_another_failure_is_left_alone() {
131 let killed = || crate::agents::failure::classify(Some(137), None, "", None);
132 let mut failure = killed();
133 explain_failure(&mut failure, &OomEvent { memory_mb: Some(8192) });
134 assert_eq!(failure.title, "Ran out of memory");
135 assert!(failure.detail.contains("8 GB"), "{}", failure.detail);
136 let mut unlimited = killed();
137 explain_failure(&mut unlimited, &OomEvent { memory_mb: None });
138 assert!(unlimited.detail.contains("Docker's own memory"), "{}", unlimited.detail);
139
140 let mut other = crate::agents::failure::classify(Some(1), None, "HTTP 429 rate_limit", None);
141 let before = other.clone();
142 explain_failure(&mut other, &OomEvent { memory_mb: Some(8192) });
143 assert_eq!(other, before);
144 }
145
146 #[test]
147 fn memory_reads_in_the_unit_a_person_would_say() {
148 assert_eq!(memory_text(256), "256 MB");
149 assert_eq!(memory_text(8192), "8 GB");
150 assert_eq!(memory_text(1536), "1.5 GB");
151 assert_eq!(memory_text(1024), "1 GB");
152 }
153}