agentmux_srv_core/backend/mem_census/
mod.rs1pub 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
33pub const LOG_TARGET: &str = "srv_mem";
35
36pub const FIRST_REPORT_AFTER: Duration = Duration::from_secs(60);
38pub const REPORT_EVERY: Duration = Duration::from_secs(300);
41
42const LOGGED_STRUCTURES: usize = 12;
44
45const JSON_MAP_ENTRY_BYTES: usize = (std::mem::size_of::<String>() + std::mem::size_of::<Value>()) * 3 / 2;
49
50#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
52pub struct Held {
53 pub name: String,
55 pub count: u64,
57 pub bytes: u64,
59 pub groups: u64,
61}
62
63#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
65pub struct MemReport {
66 pub uptime_secs: u64,
67 pub process: process::ProcessFigures,
68 pub heap: Option<alloc::HeapCounts>,
70 pub structures: Vec<Held>,
72 pub counted_bytes: u64,
74 pub census_ms: u64,
76}
77
78pub 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
89pub 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
100pub 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
126fn 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
139fn 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
157pub 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 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 let array = json!([text, text, { "k": text }]);
203 assert!(json_bytes(&array) >= 3 * std::mem::size_of::<Value>() + 3000 + JSON_MAP_ENTRY_BYTES);
204 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 #[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}