agentmux_srv/malloc_arenas.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Linux (glibc) only: cap glibc's malloc arenas, and pin its mmap threshold.
5//!
6//! srv is a multi-threaded process (a tokio worker pool and a pool of blocking
7//! threads), and glibc gives threads their own malloc arenas, up to eight per
8//! core. Each arena keeps the high-water mark of what its threads allocated and
9//! freed, so a long, busy srv holds about three times its live heap in freed
10//! memory spread over many arenas. With the cap, threads share two. Measured:
11//! 12 tool-heavy agents, srv's private memory settled at a median of 114 MB
12//! with the default and 88 MB with two arenas (paired differences 21–32 MB, the
13//! same direction in every pair), and no more CPU.
14//! docs/specs/SPEC_SRV_MALLOC_ARENA_CAP_2026_10_18.md
15//!
16//! The second setting is the mmap threshold. By default glibc raises it (up to 32 MB)
17//! every time a mapped block is freed, so after one large buffer has come and gone
18//! every later buffer of that size comes from an arena instead of its own mapping.
19//! Large, short-lived buffers (a transcript part, a serialized frame) then sit
20//! between long-lived allocations, and when they are freed their holes can't be
21//! returned to the system: a soak of 12 agents held 43 MB of freed memory beside a
22//! live heap of 46 MB. Pinning the threshold at 64 KB keeps those buffers in their own
23//! mappings, which go back at `free`. Measured, 12 agents, same build, runs side by
24//! side: after 60 rounds srv's private memory was 58.0 MB with this change and 109.6 MB
25//! without (CPU +2%); with the threshold set by the environment instead, 57.8 and 59.9 MB
26//! against 86.8 and 92.8 MB for the default.
27//! docs/specs/SPEC_SRV_MALLOC_ARENA_CAP_2026_10_18.md
28//!
29//! Windows and macOS have their own allocators, and this does nothing there.
30
31/// How many arenas srv's threads share.
32pub const ARENA_MAX: i32 = 2;
33
34/// Blocks of this size and above get their own mapping (glibc's default start is
35/// 128 KB, and it grows from there unless the value is set).
36pub const MMAP_THRESHOLD: i32 = 64 * 1024;
37
38/// Whether to apply the cap: not when the operator set `MALLOC_ARENA_MAX`
39/// (glibc reads it itself, and a deliberate setting wins).
40fn should_apply(env_value: Option<&str>) -> bool {
41 env_value.map_or(true, str::is_empty)
42}
43
44/// Whether to pin the mmap threshold: not when the operator set it, by the
45/// variable or through `GLIBC_TUNABLES`.
46fn should_pin_mmap_threshold(env_value: Option<&str>, tunables: Option<&str>) -> bool {
47 env_value.map_or(true, str::is_empty) && !tunables.is_some_and(|t| t.contains("mmap_threshold"))
48}
49
50/// Cap the arenas and pin the mmap threshold. The cap has to run before the first
51/// thread is spawned: a thread already attached to an arena keeps it, so this is
52/// the first thing `main` does, ahead of building the runtime. Returns whether the
53/// cap was set.
54pub fn apply() -> bool {
55 if should_pin_mmap_threshold(
56 std::env::var("MALLOC_MMAP_THRESHOLD_").ok().as_deref(),
57 std::env::var("GLIBC_TUNABLES").ok().as_deref(),
58 ) {
59 // SAFETY: as below. Setting the threshold also stops glibc from raising it.
60 unsafe { libc::mallopt(libc::M_MMAP_THRESHOLD, MMAP_THRESHOLD) };
61 }
62 if !should_apply(std::env::var("MALLOC_ARENA_MAX").ok().as_deref()) {
63 return false;
64 }
65 // SAFETY: `mallopt` only sets a malloc tunable; it is documented as safe to
66 // call at any time, and takes effect for arenas created after it.
67 unsafe { libc::mallopt(libc::M_ARENA_MAX, ARENA_MAX) == 1 }
68}
69
70#[cfg(test)]
71mod tests {
72 use super::*;
73
74 #[test]
75 fn it_applies_unless_the_operator_set_the_variable() {
76 assert!(should_apply(None));
77 assert!(should_apply(Some("")), "an empty variable is no setting");
78 assert!(!should_apply(Some("1")));
79 assert!(!should_apply(Some("8")), "an explicit value wins, whatever it is");
80 }
81
82 #[test]
83 fn two_arenas_is_the_measured_choice() {
84 assert_eq!(ARENA_MAX, 2);
85 }
86
87 #[test]
88 fn the_mmap_threshold_is_pinned_unless_the_operator_set_it() {
89 assert!(should_pin_mmap_threshold(None, None));
90 assert!(should_pin_mmap_threshold(Some(""), Some("glibc.malloc.arena_max=4")));
91 assert!(!should_pin_mmap_threshold(Some("131072"), None));
92 assert!(!should_pin_mmap_threshold(None, Some("glibc.malloc.mmap_threshold=1048576")));
93 }
94
95 #[test]
96 fn the_mmap_threshold_is_below_glibcs_dynamic_start() {
97 // glibc starts at 128 KB and only ever raises it; a pinned value above that would change nothing.
98 assert!(MMAP_THRESHOLD < 128 * 1024);
99 }
100}