Skip to main content

agentmux_srv_core/backend/container/
limits.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! CPU, memory and process limits of a container agent's container.
5//! `docs/specs/SPEC_CONTAINER_AGENT_RESOURCE_LIMITS_2026_10_29.md`.
6//!
7//! Every container agent is limited, existing ones too. What it gets is the agent's own setting, else the app-wide
8//! one, else a default computed from what the Docker daemon has (`docker info`: on Docker Desktop that is the VM, not
9//! the machine). The limits are put on a running container with `docker update`: a change never recreates it.
10
11use std::sync::{Arc, Mutex, OnceLock};
12use std::time::{Duration, Instant};
13
14use bollard::container::UpdateContainerOptions;
15use bollard::models::{ContainerInspectResponse, HostConfig};
16
17use super::ContainerManager;
18use crate::backend::storage::store::Store;
19
20/// App-wide default memory limit, in MB, or `"auto"`.
21pub const SETTING_MEMORY: &str = "agent:container_memory";
22/// App-wide default CPU limit, in CPUs, or `"auto"`.
23pub const SETTING_CPUS: &str = "agent:container_cpus";
24/// An image label saying how much memory a container from it needs to be useful, in MB: a developer image that builds
25/// Rust says so, and auto never gives it less (still bounded by what the daemon has).
26pub const RECOMMENDED_MIN_MEMORY_LABEL: &str = "ai.agentmux.recommended-min-memory-mb";
27
28const MIB: u64 = 1024 * 1024;
29/// The least memory Docker accepts for a container (6 MB).
30const MIN_MEMORY_BYTES: u64 = 6 * MIB;
31/// The least CPU Docker accepts for a container (0.01 CPU), in billionths of a CPU.
32const MIN_NANO_CPUS: u64 = 10_000_000;
33const GIB: u64 = 1024 * MIB;
34/// A runaway fork loop is the third way a build freezes a machine; not a setting.
35const PIDS_LIMIT: i64 = 8192;
36/// How long what `docker info` said is kept: the daemon's size changes only when Docker is restarted.
37const CAPACITY_KEPT: Duration = Duration::from_secs(300);
38
39static CONFIG: OnceLock<Arc<crate::backend::wconfig::ConfigState>> = OnceLock::new();
40
41/// Attach the live settings (bootstrap), so the app-wide limits can be read.
42pub fn install_config(config: Arc<crate::backend::wconfig::ConfigState>) {
43    let _ = CONFIG.set(config);
44}
45
46/// One limit as a person set it.
47#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
48pub enum Limit {
49    /// Not set here: the next level decides (the agent's, then the app's, then the computed default).
50    #[default]
51    Auto,
52    /// Explicitly no limit.
53    Unlimited,
54    /// MB of memory, or thousandths of a CPU.
55    Fixed(u64),
56}
57
58impl Limit {
59    /// A stored value: absent or `"auto"` is [`Limit::Auto`], `0` or `"none"` is [`Limit::Unlimited`], a positive number
60    /// is `Fixed(number * unit)`.
61    pub fn from_json(value: Option<&serde_json::Value>, unit: u64) -> Self {
62        let number = match value {
63            None | Some(serde_json::Value::Null) => return Self::Auto,
64            Some(serde_json::Value::String(s)) => match s.trim().to_ascii_lowercase().as_str() {
65                "" | "auto" => return Self::Auto,
66                "none" | "unlimited" => return Self::Unlimited,
67                other => other.parse::<f64>().ok(),
68            },
69            Some(v) => v.as_f64(),
70        };
71        match number {
72            Some(n) if n > 0.0 && n.is_finite() => Self::Fixed(((n * unit as f64).round() as u64).max(1)),
73            Some(n) if n == 0.0 => Self::Unlimited,
74            _ => Self::Auto,
75        }
76    }
77}
78
79/// An agent's own limits (`db_agent_container_limits`). [`Limit::Auto`] means "the app-wide setting decides".
80#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
81pub struct ContainerLimits {
82    pub memory: Limit,
83    /// Thousandths of a CPU.
84    pub cpus: Limit,
85}
86
87impl ContainerLimits {
88    /// The limits stored for `agent_id`; none stored, or the store failing (logged), is all [`Limit::Auto`].
89    pub fn of_agent(store: &Store, agent_id: &str) -> Self {
90        match store.container_limits_get(agent_id) {
91            Ok(Some((memory, cpus))) => Self::from_strings(&memory, &cpus),
92            Ok(None) => Self::default(),
93            Err(e) => {
94                tracing::warn!(agent_id, error = %e, "container limits: cannot read the agent's limits; using the defaults");
95                Self::default()
96            }
97        }
98    }
99
100    /// Stored text: empty is auto, `0` is no limit, a number is MB (memory) or CPUs.
101    pub fn from_strings(memory: &str, cpus: &str) -> Self {
102        let read = |text: &str, unit| Limit::from_json(Some(&serde_json::Value::String(text.to_string())), unit);
103        Self { memory: read(memory, 1), cpus: read(cpus, 1000) }
104    }
105
106    /// The app-wide defaults.
107    fn from_settings() -> Self {
108        let Some(config) = CONFIG.get() else { return Self::default() };
109        let config = config.get_full_config();
110        let extra = &config.settings.extra;
111        Self { memory: Limit::from_json(extra.get(SETTING_MEMORY), 1), cpus: Limit::from_json(extra.get(SETTING_CPUS), 1000) }
112    }
113}
114
115/// A limit as stored: `""` for auto, `"0"` for no limit, else the number (MB, or CPUs). An explicit value that is
116/// none of these is an error, where [`Limit::from_json`] is lenient with what it reads back.
117pub fn normalize(value: &serde_json::Value, what: &str) -> Result<String, String> {
118    let bad = || format!("{what} must be a positive number, 0 for no limit, or \"auto\"");
119    match Limit::from_json(Some(value), 1000) {
120        Limit::Fixed(_) => Ok(match value {
121            serde_json::Value::String(s) => s.trim().to_string(),
122            other => other.to_string(),
123        }),
124        Limit::Unlimited => Ok("0".to_string()),
125        Limit::Auto => match value {
126            serde_json::Value::Null => Ok(String::new()),
127            serde_json::Value::String(s) if s.trim().is_empty() || s.trim().eq_ignore_ascii_case("auto") => Ok(String::new()),
128            _ => Err(bad()),
129        },
130    }
131}
132
133/// What the daemon has to give.
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub struct DaemonCapacity {
136    pub mem_total: u64,
137    pub ncpu: u32,
138}
139
140/// What to do about one limit of a container.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum Target {
143    /// Not known (the daemon could not be asked): leave the container as it is. "No limit" resolves to everything
144    /// the daemon has when that is known, and to this when it is not: `docker update` takes a zero as "unchanged", so a
145    /// limit that is set can only be moved to a value, never cleared.
146    Leave,
147    /// Bytes of memory, or billionths of a CPU.
148    Set(i64),
149}
150
151/// The limits a container should carry.
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153pub struct Wanted {
154    pub memory: Target,
155    pub cpus: Target,
156}
157
158/// The default memory: half of the daemon's, never under 2 GiB (capped at what the daemon has). The spec's ceiling of
159/// "total minus 2 GiB" is never under half from 4 GiB up, and under 4 GiB the floor rules, so it needs no code. An
160/// image's recommended minimum raises the default, still bounded by the daemon's total.
161pub fn auto_memory_bytes(total: u64, recommended_min: Option<u64>) -> u64 {
162    let mut memory = (total / 2).max(2 * GIB);
163    if let Some(min) = recommended_min {
164        memory = memory.max(min);
165    }
166    memory.min(total)
167}
168
169/// The default CPUs, in thousandths: all but a quarter of the cores, at least one.
170pub fn auto_cpu_millis(ncpu: u32) -> u64 {
171    u64::from(ncpu.saturating_sub((ncpu / 4).max(1)).max(1)) * 1000
172}
173
174impl Wanted {
175    /// The limits for an agent set to `agent`, under the app-wide `app`, on a daemon of `capacity`.
176    pub fn resolve(agent: ContainerLimits, app: ContainerLimits, capacity: Option<DaemonCapacity>, recommended_min_mb: Option<u64>) -> Self {
177        let pick = |own: Limit, shared: Limit| if own == Limit::Auto { shared } else { own };
178        let memory = match pick(agent.memory, app.memory) {
179            Limit::Unlimited => capacity.map_or(Target::Leave, |c| Target::Set(c.mem_total.min(i64::MAX as u64) as i64)),
180            Limit::Fixed(mb) => Target::Set(mb.saturating_mul(MIB).clamp(MIN_MEMORY_BYTES, i64::MAX as u64) as i64),
181            Limit::Auto => match capacity {
182                Some(c) => Target::Set(auto_memory_bytes(c.mem_total, recommended_min_mb.map(|mb| mb.saturating_mul(MIB))) as i64),
183                None => Target::Leave,
184            },
185        };
186        let cpus = match pick(agent.cpus, app.cpus) {
187            Limit::Unlimited => capacity.map_or(Target::Leave, |c| Target::Set(i64::from(c.ncpu) * 1_000_000_000)),
188            // Docker refuses more CPUs than it has, or fewer than 0.01, and then the container cannot be made.
189            Limit::Fixed(millis) => {
190                let nano = millis.saturating_mul(1_000_000).clamp(MIN_NANO_CPUS, i64::MAX as u64) as i64;
191                Target::Set(capacity.map_or(nano, |c| nano.min(i64::from(c.ncpu) * 1_000_000_000)))
192            }
193            Limit::Auto => match capacity {
194                Some(c) => Target::Set((auto_cpu_millis(c.ncpu) * 1_000_000) as i64),
195                None => Target::Leave,
196            },
197        };
198        Self { memory, cpus }
199    }
200
201    /// The limits, written into the `HostConfig` of a container about to be made. A limit that is not to apply is left out.
202    pub fn apply_to(&self, host_config: &mut HostConfig) {
203        if let Target::Set(bytes) = self.memory {
204            host_config.memory = Some(bytes);
205            // Swap as large as memory: Docker's default is twice, which pages the host's swap before it kills.
206            host_config.memory_swap = Some(bytes);
207        }
208        if let Target::Set(nano) = self.cpus {
209            host_config.nano_cpus = Some(nano);
210        }
211        host_config.pids_limit = Some(PIDS_LIMIT);
212    }
213
214    /// The `docker update` that takes a container with `current` to these limits, or `None` when it already has them.
215    /// Memory and swap travel in one request, so the pair is valid whichever way the limit moves.
216    pub fn update_from(&self, current: Option<&HostConfig>) -> Option<UpdateContainerOptions<String>> {
217        let have = |f: fn(&HostConfig) -> Option<i64>| current.and_then(f).unwrap_or(0);
218        let mut update = UpdateContainerOptions::<String>::default();
219        let mut changed = false;
220        match self.memory {
221            Target::Set(bytes) if have(|h| h.memory) != bytes || have(|h| h.memory_swap) != bytes => {
222                update.memory = Some(bytes);
223                update.memory_swap = Some(bytes);
224                changed = true;
225            }
226            _ => {}
227        }
228        match self.cpus {
229            Target::Set(nano) if have(|h| h.nano_cpus) != nano => {
230                update.nano_cpus = Some(nano);
231                changed = true;
232            }
233            _ => {}
234        }
235        if have(|h| h.pids_limit) != PIDS_LIMIT {
236            update.pids_limit = Some(PIDS_LIMIT);
237            changed = true;
238        }
239        changed.then_some(update)
240    }
241}
242
243/// The recommended minimum memory an image says it needs, in MB, from a container's inspect.
244fn recommended_min_mb(details: &ContainerInspectResponse) -> Option<u64> {
245    details.config.as_ref()?.labels.as_ref()?.get(RECOMMENDED_MIN_MEMORY_LABEL)?.trim().parse().ok()
246}
247
248fn capacity_cache() -> &'static Mutex<Option<(Instant, DaemonCapacity)>> {
249    static CACHE: OnceLock<Mutex<Option<(Instant, DaemonCapacity)>>> = OnceLock::new();
250    CACHE.get_or_init(Default::default)
251}
252
253impl ContainerManager {
254    /// What the daemon has, from `docker info`; kept for a few minutes. `None` when it can't be read (logged).
255    pub async fn daemon_capacity(&self) -> Option<DaemonCapacity> {
256        if let Some((at, capacity)) = *capacity_cache().lock().unwrap() {
257            if at.elapsed() < CAPACITY_KEPT {
258                return Some(capacity);
259            }
260        }
261        let info = match self.inner.docker.info().await {
262            Ok(info) => info,
263            Err(e) => {
264                tracing::warn!(error = %e, "container limits: can't read the daemon's size (docker info); not applying a default limit");
265                return None;
266            }
267        };
268        let capacity = DaemonCapacity {
269            mem_total: info.mem_total.filter(|m| *m > 0)? as u64,
270            ncpu: info.ncpu.filter(|n| *n > 0).map(|n| n as u32)?,
271        };
272        *capacity_cache().lock().unwrap() = Some((Instant::now(), capacity));
273        Some(capacity)
274    }
275
276    /// The limits `agent` should carry on this daemon, under the app-wide settings.
277    pub async fn wanted_limits(&self, agent: ContainerLimits, recommended_min_mb: Option<u64>) -> Wanted {
278        Wanted::resolve(agent, ContainerLimits::from_settings(), self.daemon_capacity().await, recommended_min_mb)
279    }
280
281    /// The limits `container_name` has or would be given: as [`Self::limits_apply`] sets them, with its image's
282    /// recommended minimum. Without such a container, no label is known.
283    pub async fn wanted_limits_for_container(&self, container_name: &str, agent: ContainerLimits) -> Wanted {
284        let recommended = self.inner.docker.inspect_container(container_name, None).await.ok().and_then(|d| recommended_min_mb(&d));
285        self.wanted_limits(agent, recommended).await
286    }
287
288    /// The limits for a container about to be made from `image`, whose labels may name a recommended minimum.
289    pub(super) async fn wanted_limits_for_new(&self, image: &str, agent: ContainerLimits) -> Wanted {
290        let labels = self.inner.docker.inspect_image(image).await.ok().and_then(|i| i.config).and_then(|c| c.labels);
291        let recommended = labels.as_ref().and_then(|l| l.get(RECOMMENDED_MIN_MEMORY_LABEL)).and_then(|v| v.trim().parse().ok());
292        self.wanted_limits(agent, recommended).await
293    }
294
295    /// Puts the limits on an existing container (one made before they existed, or whose setting changed), without
296    /// recreating it. A failure is logged and the container is left as it is. `None`: there is no such container (it
297    /// takes the limits when it is made); `Some(true)`: it has them now; `Some(false)`: Docker refused the update.
298    pub async fn limits_apply(&self, container_name: &str, agent: ContainerLimits) -> Option<bool> {
299        let details = self.inner.docker.inspect_container(container_name, None).await.ok()?;
300        let wanted = self.wanted_limits(agent, recommended_min_mb(&details)).await;
301        let Some(update) = wanted.update_from(details.host_config.as_ref()) else { return Some(true) };
302        match self.inner.docker.update_container(container_name, update).await {
303            Ok(()) => {
304                tracing::info!(container = container_name, ?wanted, "container limits updated");
305                Some(true)
306            }
307            Err(e) => {
308                tracing::warn!(container = container_name, error = %e, ?wanted, "container limits: docker refused the update; the container keeps its limits");
309                Some(false)
310            }
311        }
312    }
313}
314
315#[cfg(test)]
316mod tests;