Skip to main content

agentmux_srv_core/backend/container/
oom.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Telling a container agent's user that something in the container was stopped for going over its memory limit,
5//! instead of a bare exit 137. `docs/specs/SPEC_CONTAINER_AGENT_RESOURCE_LIMITS_2026_10_29.md` ยง5.
6//!
7//! The evidence is the container cgroup's own `oom_kill` counter (`memory.events` on cgroup v2, `memory.oom_control` on
8//! v1): read when a turn starts and again when it ends, a rise means the kernel killed a process in this container in
9//! between. An exit code of 137 alone is not proof (a stop is SIGKILL too), and the usual victim is not the turn but a
10//! child of the CLI, such as the `cargo` of a Bash tool, so the turn can end cleanly and still have been hit.
11
12use futures_util::StreamExt as _;
13use std::sync::Arc;
14
15use super::ContainerManager;
16
17/// Prints the cgroup's OOM counters, whichever cgroup version the container is on.
18const READ_COUNTER: &str = "cat /sys/fs/cgroup/memory.events 2>/dev/null || cat /sys/fs/cgroup/memory/memory.oom_control 2>/dev/null";
19
20/// The longest the counter is waited for; a counter that can't be read in that time is treated as unreadable.
21const READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
22
23/// The `oom_kill` value in the text of `memory.events` / `memory.oom_control`.
24pub 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/// A process of the container was killed for memory during a turn.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct OomEvent {
34    /// The memory limit the container has, in MB; `None` when it has none (the daemon itself ran short).
35    pub memory_mb: Option<u64>,
36}
37
38impl ContainerManager {
39    /// How many processes the kernel has killed in this container for memory since it started; `None` when it can't be read.
40    /// Bounded: a turn waits on it before it starts, where a stop can't reach it.
41    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    /// Whether a process was killed for memory since the count was `before`.
56    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
66/// What the failure of a turn that ended by SIGKILL says when memory was the cause.
67pub 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
78/// `8192` as `8 GB`, `1536` as `1.5 GB`, `256` as `256 MB`.
79pub 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
87/// Writes the pane row for an [`OomEvent`] of the pane `block_id`.
88pub 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}