Skip to main content

agentmux_srv_core/backend/mem_census/
alloc.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How much the process has allocated and not freed.
5//!
6//! The operating system reports what a process has committed, not how much of that is in use: a heap
7//! that grew for one large short-lived buffer can keep the memory after the buffer is freed. To tell
8//! the two apart srv counts its own allocations. [`CountingAlloc`] is the system allocator with three
9//! counters in front of it; srv's `main.rs` installs it, and [`counts`] reads them. Committed memory
10//! far above the live bytes is memory the heap is keeping, not memory a structure holds.
11//!
12//! It counts what goes through Rust's allocator. A C library's own `malloc` (SQLite's page caches) is
13//! not in it.
14
15use std::alloc::{GlobalAlloc, Layout, System};
16use std::sync::atomic::{AtomicIsize, AtomicUsize, Ordering::Relaxed};
17
18/// An allocation of at least this many bytes is also counted as a large one: these are the buffers
19/// that push a heap up (a transcript read whole, a serialized reply).
20pub const LARGE_BYTES: usize = 1024 * 1024;
21
22/// The counters are kept in this many separate places, each on its own cache lines, so threads that
23/// allocate at the same time do not all write one line. A thread may free on another stripe than it
24/// allocated on: a single stripe can go negative, only the sum means anything.
25const STRIPES: usize = 16;
26
27#[repr(align(128))]
28struct Stripe {
29    live_bytes: AtomicIsize,
30    live_blocks: AtomicIsize,
31    allocated_bytes: AtomicUsize,
32}
33
34static COUNTS: [Stripe; STRIPES] = [const {
35    Stripe { live_bytes: AtomicIsize::new(0), live_blocks: AtomicIsize::new(0), allocated_bytes: AtomicUsize::new(0) }
36}; STRIPES];
37static LARGE_COUNT: AtomicUsize = AtomicUsize::new(0);
38static LARGE_BYTES_TOTAL: AtomicUsize = AtomicUsize::new(0);
39static LARGEST_BYTES: AtomicUsize = AtomicUsize::new(0);
40
41/// The stripe for the calling thread, chosen by where its stack is: stacks are megabytes apart, so
42/// two threads rarely share one, and nothing here can allocate (a thread-local with a destructor
43/// could).
44#[inline]
45fn stripe() -> &'static Stripe {
46    let here = 0u8;
47    &COUNTS[((std::ptr::addr_of!(here) as usize) >> 20) % STRIPES]
48}
49
50#[cold]
51fn count_large(bytes: usize) {
52    LARGE_COUNT.fetch_add(1, Relaxed);
53    LARGE_BYTES_TOTAL.fetch_add(bytes, Relaxed);
54    LARGEST_BYTES.fetch_max(bytes, Relaxed);
55}
56
57#[inline]
58fn count_alloc(bytes: usize) {
59    let s = stripe();
60    s.live_bytes.fetch_add(bytes as isize, Relaxed);
61    s.live_blocks.fetch_add(1, Relaxed);
62    s.allocated_bytes.fetch_add(bytes, Relaxed);
63    if bytes >= LARGE_BYTES {
64        count_large(bytes);
65    }
66}
67
68#[inline]
69fn count_free(bytes: usize) {
70    let s = stripe();
71    s.live_bytes.fetch_sub(bytes as isize, Relaxed);
72    s.live_blocks.fetch_sub(1, Relaxed);
73}
74
75#[inline]
76fn count_resize(old: usize, new: usize) {
77    let s = stripe();
78    s.live_bytes.fetch_add(new as isize - old as isize, Relaxed);
79    if new > old {
80        s.allocated_bytes.fetch_add(new - old, Relaxed);
81        if new >= LARGE_BYTES {
82            count_large(new);
83        }
84    }
85}
86
87/// The system allocator, counted. It changes nothing about where memory comes from.
88pub struct CountingAlloc;
89
90// SAFETY: every call is passed to `System` unchanged, with the caller's own layout and pointer; the
91// counters are atomics and never allocate.
92unsafe impl GlobalAlloc for CountingAlloc {
93    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
94        // SAFETY: the caller's contract for `alloc` is `System.alloc`'s.
95        let ptr = unsafe { System.alloc(layout) };
96        if !ptr.is_null() {
97            count_alloc(layout.size());
98        }
99        ptr
100    }
101
102    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
103        // SAFETY: the caller's contract for `alloc_zeroed` is `System.alloc_zeroed`'s.
104        let ptr = unsafe { System.alloc_zeroed(layout) };
105        if !ptr.is_null() {
106            count_alloc(layout.size());
107        }
108        ptr
109    }
110
111    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
112        // SAFETY: `ptr` came from this allocator with `layout`, so from `System` with `layout`.
113        unsafe { System.dealloc(ptr, layout) };
114        count_free(layout.size());
115    }
116
117    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
118        // SAFETY: `ptr` came from this allocator with `layout`, so from `System` with `layout`.
119        let new_ptr = unsafe { System.realloc(ptr, layout, new_size) };
120        if !new_ptr.is_null() {
121            count_resize(layout.size(), new_size);
122        }
123        new_ptr
124    }
125}
126
127/// What [`CountingAlloc`] has counted since the process started.
128#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
129pub struct HeapCounts {
130    /// Bytes allocated and not freed.
131    pub live_bytes: u64,
132    /// Allocations not freed.
133    pub live_blocks: u64,
134    /// Every byte ever allocated: the difference between two readings is the churn in between.
135    pub allocated_total_bytes: u64,
136    /// Allocations of [`LARGE_BYTES`] or more, ever.
137    pub large_count: u64,
138    /// Their bytes together.
139    pub large_total_bytes: u64,
140    /// The largest single allocation.
141    pub largest_bytes: u64,
142}
143
144fn read() -> HeapCounts {
145    let (mut live_bytes, mut live_blocks, mut allocated) = (0isize, 0isize, 0usize);
146    for s in &COUNTS {
147        live_bytes = live_bytes.wrapping_add(s.live_bytes.load(Relaxed));
148        live_blocks = live_blocks.wrapping_add(s.live_blocks.load(Relaxed));
149        allocated = allocated.wrapping_add(s.allocated_bytes.load(Relaxed));
150    }
151    HeapCounts {
152        live_bytes: live_bytes.max(0) as u64,
153        live_blocks: live_blocks.max(0) as u64,
154        allocated_total_bytes: allocated as u64,
155        large_count: LARGE_COUNT.load(Relaxed) as u64,
156        large_total_bytes: LARGE_BYTES_TOTAL.load(Relaxed) as u64,
157        largest_bytes: LARGEST_BYTES.load(Relaxed) as u64,
158    }
159}
160
161/// The counts, or `None` in a process that does not allocate through [`CountingAlloc`] (a test
162/// binary, a helper program): there nothing was ever counted.
163pub fn counts() -> Option<HeapCounts> {
164    let counts = read();
165    (counts.allocated_total_bytes > 0).then_some(counts)
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    /// One test, because the counters are the process's: two tests running at once would read each
173    /// other's allocations. The test binary itself does not allocate through `CountingAlloc`, so
174    /// nothing else moves them.
175    #[test]
176    fn allocations_are_counted_until_they_are_freed_on_any_thread() {
177        let before = read();
178        let small = Layout::from_size_align(4096, 8).unwrap();
179        // SAFETY: a valid non-zero layout; the pointer is resized and freed below with the layouts it
180        // was given.
181        let ptr = unsafe { CountingAlloc.alloc(small) };
182        assert!(!ptr.is_null());
183        let held = read();
184        assert_eq!(held.live_bytes - before.live_bytes, 4096);
185        assert_eq!(held.live_blocks - before.live_blocks, 1);
186        assert_eq!(held.allocated_total_bytes - before.allocated_total_bytes, 4096);
187        assert_eq!(held.large_count, before.large_count, "4 KiB is not a large allocation");
188
189        // Growing it past the large size counts one large allocation, and the block count stays.
190        let big = 2 * LARGE_BYTES;
191        // SAFETY: `ptr` came from `alloc(small)`; `big` is non-zero and within `isize`.
192        let ptr = unsafe { CountingAlloc.realloc(ptr, small, big) };
193        assert!(!ptr.is_null());
194        let grown = read();
195        assert_eq!(grown.live_bytes - before.live_bytes, big as u64);
196        assert_eq!(grown.live_blocks - before.live_blocks, 1);
197        assert_eq!(grown.large_count - before.large_count, 1);
198        assert_eq!(grown.large_total_bytes - before.large_total_bytes, big as u64);
199        assert!(grown.largest_bytes >= big as u64);
200        assert_eq!(counts(), Some(grown), "once something was counted, the counts are reported");
201
202        // Freed on another thread, so most likely on another stripe: the sums still come back.
203        let grown_layout = Layout::from_size_align(big, 8).unwrap();
204        let addr = ptr as usize;
205        std::thread::spawn(move || {
206            // SAFETY: the block from `realloc` above, with its current size and the same alignment;
207            // nothing else uses it.
208            unsafe { CountingAlloc.dealloc(addr as *mut u8, grown_layout) };
209        })
210        .join()
211        .unwrap();
212        let after = read();
213        assert_eq!(after.live_bytes, before.live_bytes);
214        assert_eq!(after.live_blocks, before.live_blocks);
215        assert_eq!(after.allocated_total_bytes - before.allocated_total_bytes, big as u64, "a freed byte stays in the total");
216    }
217}