Skip to main content

agentmux_srv_core/backend/mem_census/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! srv's own memory, and what holds it: one report, logged every few minutes and served to
5//! `muxspect memory`.
6//!
7//! Three things are read side by side, because the question on a machine where srv has grown large
8//! is which of them the memory is in:
9//!
10//! 1. What the operating system has given the process ([`process`]).
11//! 2. What srv has allocated and not freed ([`alloc`]). Committed memory far above this is memory the
12//!    heap keeps after it was freed, and no structure holds it.
13//! 3. The structures known to grow with use, each with its count and an estimate of its bytes
14//!    ([`Held`]). Live bytes far above their sum is a structure this census does not know.
15//!
16//! The bytes of a structure are an estimate: the content of its strings and JSON values plus the
17//! room its lists reserve, not the allocator's rounding. Taking the census walks each structure
18//! under its own lock, one at a time; the report says how long that took.
19//!
20//! Report: `docs/reports/REPORT_SRV_MEMORY_UNDER_400MB_2026_12_01.md` (step 0 of its plan).
21
22pub mod alloc;
23pub mod process;
24
25use std::time::{Duration, Instant};
26
27use serde_json::Value;
28
29use crate::backend::dock_snapshot::DockSnapshotCache;
30use crate::backend::mps::Broker;
31use crate::backend::subagent_watcher::{SubagentEvent, SubagentEventType};
32
33/// The log line's target: `muxlog srv grep srv_mem`.
34pub const LOG_TARGET: &str = "srv_mem";
35
36/// The first report comes this long after start, when the windows and agents are restored.
37pub const FIRST_REPORT_AFTER: Duration = Duration::from_secs(60);
38/// Then one report per interval. The census walks every kept event, so it is not taken every few
39/// seconds; a day of use still gives 288 readings.
40pub const REPORT_EVERY: Duration = Duration::from_secs(300);
41
42/// How many structures the log line names, largest first. `muxspect memory` lists all of them.
43const LOGGED_STRUCTURES: usize = 12;
44
45/// A JSON object is a B-tree of keys and values. This is the room one entry takes in it besides the
46/// key's text and the value's own content: the key's `String`, the `Value`, and the usual third of a
47/// node that is empty.
48const JSON_MAP_ENTRY_BYTES: usize = (std::mem::size_of::<String>() + std::mem::size_of::<Value>()) * 3 / 2;
49
50/// One structure that grows with use: how much it holds now.
51#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
52pub struct Held {
53    /// The structure; for the broker's kept events, with the event's name.
54    pub name: String,
55    /// Entries held (events, nodes, frames).
56    pub count: u64,
57    /// An estimate of their bytes on the heap.
58    pub bytes: u64,
59    /// How many lists the entries are in (scopes, subagents, panes); 0 where there is one list.
60    pub groups: u64,
61}
62
63/// One reading of srv's memory.
64#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
65pub struct MemReport {
66    pub uptime_secs: u64,
67    pub process: process::ProcessFigures,
68    /// `None` in a process that does not count its allocations (see [`alloc::counts`]).
69    pub heap: Option<alloc::HeapCounts>,
70    /// Largest first.
71    pub structures: Vec<Held>,
72    /// The structures' bytes together.
73    pub counted_bytes: u64,
74    /// How long the census of the structures took.
75    pub census_ms: u64,
76}
77
78/// An estimate of the heap bytes behind a JSON value (not the `Value` itself, which its holder
79/// counts): string text, array slots and object entries, all the way down.
80pub fn json_bytes(value: &Value) -> usize {
81    match value {
82        Value::Null | Value::Bool(_) | Value::Number(_) => 0,
83        Value::String(text) => text.capacity(),
84        Value::Array(items) => items.capacity() * std::mem::size_of::<Value>() + items.iter().map(json_bytes).sum::<usize>(),
85        Value::Object(entries) => entries.iter().map(|(key, item)| key.len() + JSON_MAP_ENTRY_BYTES + json_bytes(item)).sum(),
86    }
87}
88
89/// An estimate of the heap bytes behind one subagent event.
90pub fn subagent_event_bytes(event: &SubagentEvent) -> usize {
91    let content = match &event.event_type {
92        SubagentEventType::Text { content } | SubagentEventType::Result { content } => content.capacity(),
93        SubagentEventType::ToolUse { name, input } => name.capacity() + json_bytes(input),
94        SubagentEventType::ToolResult { preview, .. } => preview.capacity(),
95        SubagentEventType::Progress { output } => output.capacity(),
96    };
97    event.agent_id.capacity() + content
98}
99
100/// Take a reading. Blocking work (a walk of every counted structure, each under its own lock): call
101/// it from the blocking pool.
102pub fn collect(broker: &Broker, dock: &DockSnapshotCache) -> MemReport {
103    let started = Instant::now();
104    let mut structures = broker.kept_events_census();
105    structures.push(dock.census());
106    structures.push(crate::backend::storage::filestore::frames::cache_census());
107    if let Some(watcher) = crate::backend::subagent_watcher::global() {
108        structures.push(watcher.events_census());
109    }
110    let census_ms = started.elapsed().as_millis() as u64;
111    assemble(crate::backend::sysinfo::uptime_secs(), process::own(), alloc::counts(), structures, census_ms)
112}
113
114fn assemble(
115    uptime_secs: u64,
116    process: process::ProcessFigures,
117    heap: Option<alloc::HeapCounts>,
118    mut structures: Vec<Held>,
119    census_ms: u64,
120) -> MemReport {
121    structures.sort_by(|a, b| b.bytes.cmp(&a.bytes).then_with(|| a.name.cmp(&b.name)));
122    let counted_bytes = structures.iter().map(|held| held.bytes).sum();
123    MemReport { uptime_secs, process, heap, structures, counted_bytes, census_ms }
124}
125
126/// Bytes as megabytes with one decimal: `12.3`.
127fn mb(bytes: u64) -> String {
128    format!("{:.1}", bytes as f64 / (1024.0 * 1024.0))
129}
130
131fn mb_or_unknown(bytes: Option<u64>) -> String {
132    bytes.map_or_else(|| "unknown".to_string(), mb)
133}
134
135fn count_or_unknown(count: Option<u32>) -> String {
136    count.map_or_else(|| "unknown".to_string(), |n| n.to_string())
137}
138
139/// The structures as one log field, largest first: `name=count/MB` and, where there are several
140/// lists, `/lists`. Past [`LOGGED_STRUCTURES`] the rest are summed.
141fn structures_field(structures: &[Held]) -> String {
142    let mut parts: Vec<String> = structures
143        .iter()
144        .take(LOGGED_STRUCTURES)
145        .map(|held| {
146            let lists = if held.groups > 0 { format!("/{} lists", held.groups) } else { String::new() };
147            format!("{}={}/{}MB{lists}", held.name, held.count, mb(held.bytes))
148        })
149        .collect();
150    let rest = &structures[structures.len().min(LOGGED_STRUCTURES)..];
151    if !rest.is_empty() {
152        parts.push(format!("{} more={}MB", rest.len(), mb(rest.iter().map(|held| held.bytes).sum())));
153    }
154    parts.join("; ")
155}
156
157/// Write the reading as one log line.
158pub fn log(report: &MemReport) {
159    let heap = report.heap.unwrap_or_default();
160    let counted = report.heap.is_some();
161    tracing::info!(
162        target: LOG_TARGET,
163        uptime_secs = report.uptime_secs,
164        private_mb = %mb_or_unknown(report.process.private_bytes),
165        resident_mb = %mb(report.process.resident_bytes),
166        threads = %count_or_unknown(report.process.threads),
167        handles = %count_or_unknown(report.process.handles),
168        heap_counted = counted,
169        heap_live_mb = %mb(heap.live_bytes),
170        heap_live_blocks = heap.live_blocks,
171        heap_allocated_total_mb = %mb(heap.allocated_total_bytes),
172        large_allocs = heap.large_count,
173        large_allocs_total_mb = %mb(heap.large_total_bytes),
174        largest_alloc_mb = %mb(heap.largest_bytes),
175        structures_mb = %mb(report.counted_bytes),
176        structures = %structures_field(&report.structures),
177        census_ms = report.census_ms,
178        "srv memory"
179    );
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use serde_json::json;
186
187    fn held(name: &str, count: u64, bytes: u64, groups: u64) -> Held {
188        Held { name: name.to_string(), count, bytes, groups }
189    }
190
191    #[test]
192    fn a_json_value_is_sized_by_its_text_and_its_entries() {
193        assert_eq!(json_bytes(&json!(null)), 0);
194        assert_eq!(json_bytes(&json!(12.5)), 0);
195        let text = "x".repeat(1000);
196        assert!(json_bytes(&json!(text)) >= 1000);
197        // An object: each key, an entry's room, and the value's own content.
198        let object = json!({ "text": text, "n": 1 });
199        let expected = "text".len() + "n".len() + 2 * JSON_MAP_ENTRY_BYTES + 1000;
200        assert!(json_bytes(&object) >= expected, "{} < {expected}", json_bytes(&object));
201        // An array: a slot per item, and what the items hold.
202        let array = json!([text, text, { "k": text }]);
203        assert!(json_bytes(&array) >= 3 * std::mem::size_of::<Value>() + 3000 + JSON_MAP_ENTRY_BYTES);
204        // Nesting adds up, it does not multiply.
205        assert!(json_bytes(&json!({ "a": { "b": [text] } })) < 2000);
206    }
207
208    #[test]
209    fn a_subagent_event_is_sized_by_what_it_carries() {
210        let event = |event_type| SubagentEvent { agent_id: "a".repeat(10), event_type, timestamp: 1 };
211        let text = "y".repeat(500);
212        assert!(subagent_event_bytes(&event(SubagentEventType::Text { content: text.clone() })) >= 510);
213        assert!(subagent_event_bytes(&event(SubagentEventType::Progress { output: text.clone() })) >= 510);
214        assert!(subagent_event_bytes(&event(SubagentEventType::ToolResult { is_error: false, preview: text.clone() })) >= 510);
215        let tool = SubagentEventType::ToolUse { name: "Bash".to_string(), input: json!({ "command": text }) };
216        assert!(subagent_event_bytes(&event(tool)) >= 10 + 4 + 500 + JSON_MAP_ENTRY_BYTES);
217    }
218
219    #[test]
220    fn a_report_lists_the_largest_structure_first_and_sums_them() {
221        let structures = vec![held("small", 1, 10, 0), held("large", 5, 3000, 2), held("middle", 2, 200, 0)];
222        let report = assemble(7, process::ProcessFigures::default(), None, structures, 3);
223        let names: Vec<&str> = report.structures.iter().map(|h| h.name.as_str()).collect();
224        assert_eq!(names, ["large", "middle", "small"]);
225        assert_eq!(report.counted_bytes, 3210);
226        assert_eq!((report.uptime_secs, report.census_ms), (7, 3));
227    }
228
229    #[test]
230    fn the_log_field_names_each_structure_with_its_count_size_and_lists() {
231        let mib = 1024 * 1024;
232        let structures = vec![held("kept events: bash:output", 2048, 3 * mib, 3), held("decoded frame cache", 12, mib / 2, 0)];
233        assert_eq!(structures_field(&structures), "kept events: bash:output=2048/3.0MB/3 lists; decoded frame cache=12/0.5MB");
234        assert_eq!(structures_field(&[]), "");
235    }
236
237    #[test]
238    fn the_log_field_sums_what_it_does_not_name() {
239        let mib = 1024 * 1024;
240        let structures: Vec<Held> = (0..LOGGED_STRUCTURES + 3).map(|i| held(&format!("s{i}"), 1, mib, 0)).collect();
241        let field = structures_field(&structures);
242        assert_eq!(field.matches(';').count(), LOGGED_STRUCTURES, "{field}");
243        assert!(field.ends_with("; 3 more=3.0MB"), "{field}");
244    }
245
246    #[test]
247    fn unknown_figures_say_so() {
248        assert_eq!(mb_or_unknown(None), "unknown");
249        assert_eq!(mb_or_unknown(Some(1024 * 1024 * 3 / 2)), "1.5");
250        assert_eq!(count_or_unknown(None), "unknown");
251        assert_eq!(count_or_unknown(Some(187)), "187");
252    }
253
254    /// A reading of this test process: the structures it can reach are there, and the census is
255    /// quick when they are empty.
256    #[test]
257    fn a_reading_has_the_process_and_every_counted_structure() {
258        let report = collect(&Broker::new(), &DockSnapshotCache::new());
259        assert!(report.process.resident_bytes > 0);
260        let names: Vec<&str> = report.structures.iter().map(|h| h.name.as_str()).collect();
261        assert!(names.contains(&"tool status cache"), "{names:?}");
262        assert!(names.contains(&"decoded frame cache"), "{names:?}");
263        log(&report);
264    }
265}