Skip to main content

aft_store/
heap.rs

1//! The heap bytes of in-memory structures, for AFT's memory census.
2//!
3//! A figure is measured by walking the live structure and adding up what
4//! each part owns on the heap, read from the containers' own lengths and
5//! capacities:
6//!
7//! - `String`, `Vec` and `PathBuf`: capacity times the element size.
8//! - `Box`, and the shared allocation of an `Arc` or `Rc`: the size of the
9//!   value, plus an `Arc`'s or `Rc`'s two reference counts.
10//! - `HashMap` and `HashSet`: the table the standard library allocates for
11//!   the map's capacity: one slot and one control byte per bucket, and one
12//!   group of control bytes more.
13//! - `BTreeMap` and `BTreeSet`: one node of eleven slots for every eleven
14//!   entries, each slot the size of an entry. The standard library does not
15//!   say how full its nodes are; a node can be as little as half full, and
16//!   an internal node also holds its edges, so a B-tree's figure is a lower
17//!   bound.
18//!
19//! An allocation reached through more than one `Arc` or `Rc` is counted
20//! once per walk ([`Seen`]). The allocator's own bookkeeping and size-class
21//! rounding are not counted, and nothing here waits for a lock: a part held
22//! by another thread is left out and counted in [`Seen::contended`].
23
24use std::borrow::Cow;
25use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
26use std::mem::{size_of, size_of_val};
27use std::path::PathBuf;
28use std::sync::{Arc, Mutex, OnceLock, RwLock, TryLockError};
29
30/// What a value owns on the heap, beyond its own inline size.
31pub trait HeapBytes {
32    /// The bytes this value owns on the heap; an allocation `seen` has
33    /// already counted adds nothing.
34    fn heap_bytes(&self, seen: &mut Seen) -> usize;
35}
36
37/// One walk's memory of the shared allocations it has counted, and of the
38/// parts it could not read without waiting.
39#[derive(Debug, Default)]
40pub struct Seen {
41    shared: HashSet<usize>,
42    contended: usize,
43}
44
45impl Seen {
46    #[must_use]
47    pub fn new() -> Self {
48        Self::default()
49    }
50
51    /// Whether the shared allocation at `address` is met for the first time
52    /// in this walk; it is counted only then.
53    pub fn first<T: ?Sized>(&mut self, address: *const T) -> bool {
54        self.shared.insert(address.cast::<()>() as usize)
55    }
56
57    /// Marks the shared allocation at `address` as counted elsewhere, so
58    /// this walk leaves it out.
59    pub fn counted_elsewhere<T: ?Sized>(&mut self, address: *const T) {
60        self.shared.insert(address.cast::<()>() as usize);
61    }
62
63    /// Records that a part was held by another thread and left out.
64    pub fn contend(&mut self) {
65        self.contended += 1;
66    }
67
68    /// How many parts this walk left out because another thread held them.
69    #[must_use]
70    pub fn contended(&self) -> usize {
71        self.contended
72    }
73}
74
75/// The heap bytes of `value` in a walk of its own.
76pub fn heap_bytes_of<T: HeapBytes + ?Sized>(value: &T) -> usize {
77    value.heap_bytes(&mut Seen::new())
78}
79
80/// Implements [`HeapBytes`] for a struct as the sum of its fields. Every
81/// field must be named: the struct is destructured without `..`, so a field
82/// added later fails to compile until it is listed here.
83#[macro_export]
84macro_rules! heap_bytes_of_fields {
85    ($ty:ty { $($field:ident),* $(,)? }) => {
86        impl $crate::heap::HeapBytes for $ty {
87            fn heap_bytes(&self, seen: &mut $crate::heap::Seen) -> usize {
88                let Self { $($field),* } = self;
89                let _ = &seen;
90                0 $(+ $crate::heap::HeapBytes::heap_bytes($field, seen))*
91            }
92        }
93    };
94}
95
96/// Implements [`HeapBytes`] as zero for types that own nothing on the heap.
97#[macro_export]
98macro_rules! heap_bytes_none {
99    ($($ty:ty),* $(,)?) => {
100        $(
101            impl $crate::heap::HeapBytes for $ty {
102                fn heap_bytes(&self, _seen: &mut $crate::heap::Seen) -> usize {
103                    0
104                }
105            }
106        )*
107    };
108}
109
110heap_bytes_none!(
111    (),
112    bool,
113    char,
114    u8,
115    u16,
116    u32,
117    u64,
118    u128,
119    usize,
120    i8,
121    i16,
122    i32,
123    i64,
124    i128,
125    isize,
126    f32,
127    f64,
128    str,
129    &'static str,
130    std::time::SystemTime,
131    std::time::Instant,
132    std::time::Duration,
133    std::ops::Range<usize>,
134    std::sync::atomic::AtomicBool,
135    std::sync::atomic::AtomicU32,
136    std::sync::atomic::AtomicU64,
137    std::sync::atomic::AtomicUsize,
138    crate::ids::CheckoutId,
139    crate::ids::ContentKey,
140    crate::ids::Digest128,
141    crate::ids::FamilyId,
142    crate::ids::Generation,
143    crate::ids::SegmentId,
144    crate::ids::WriterIncarnation,
145);
146
147impl HeapBytes for String {
148    fn heap_bytes(&self, _seen: &mut Seen) -> usize {
149        self.capacity()
150    }
151}
152
153impl HeapBytes for PathBuf {
154    fn heap_bytes(&self, _seen: &mut Seen) -> usize {
155        self.capacity()
156    }
157}
158
159impl HeapBytes for Cow<'static, str> {
160    fn heap_bytes(&self, _seen: &mut Seen) -> usize {
161        match self {
162            Cow::Borrowed(_) => 0,
163            Cow::Owned(owned) => owned.capacity(),
164        }
165    }
166}
167
168impl<T: HeapBytes> HeapBytes for [T] {
169    fn heap_bytes(&self, seen: &mut Seen) -> usize {
170        self.iter().map(|item| item.heap_bytes(seen)).sum()
171    }
172}
173
174impl<T: HeapBytes, const N: usize> HeapBytes for [T; N] {
175    fn heap_bytes(&self, seen: &mut Seen) -> usize {
176        self.as_slice().heap_bytes(seen)
177    }
178}
179
180impl<T: HeapBytes> HeapBytes for Vec<T> {
181    fn heap_bytes(&self, seen: &mut Seen) -> usize {
182        self.capacity() * size_of::<T>() + self.as_slice().heap_bytes(seen)
183    }
184}
185
186impl<T: HeapBytes + ?Sized> HeapBytes for Box<T> {
187    fn heap_bytes(&self, seen: &mut Seen) -> usize {
188        size_of_val::<T>(self) + (**self).heap_bytes(seen)
189    }
190}
191
192/// The bytes of an `Arc`'s or `Rc`'s strong and weak counts, stored in its
193/// shared allocation beside its value.
194pub const COUNTS: usize = 2 * size_of::<usize>();
195
196impl<T: HeapBytes + ?Sized> HeapBytes for Arc<T> {
197    fn heap_bytes(&self, seen: &mut Seen) -> usize {
198        if seen.first(Arc::as_ptr(self)) {
199            COUNTS + size_of_val::<T>(self) + (**self).heap_bytes(seen)
200        } else {
201            0
202        }
203    }
204}
205
206impl<T: HeapBytes + ?Sized> HeapBytes for std::rc::Rc<T> {
207    fn heap_bytes(&self, seen: &mut Seen) -> usize {
208        if seen.first(std::rc::Rc::as_ptr(self)) {
209            COUNTS + size_of_val::<T>(self) + (**self).heap_bytes(seen)
210        } else {
211            0
212        }
213    }
214}
215
216impl<T: HeapBytes> HeapBytes for Option<T> {
217    fn heap_bytes(&self, seen: &mut Seen) -> usize {
218        self.as_ref().map_or(0, |value| value.heap_bytes(seen))
219    }
220}
221
222impl<A: HeapBytes, B: HeapBytes> HeapBytes for (A, B) {
223    fn heap_bytes(&self, seen: &mut Seen) -> usize {
224        self.0.heap_bytes(seen) + self.1.heap_bytes(seen)
225    }
226}
227
228impl<A: HeapBytes, B: HeapBytes, C: HeapBytes> HeapBytes for (A, B, C) {
229    fn heap_bytes(&self, seen: &mut Seen) -> usize {
230        self.0.heap_bytes(seen) + self.1.heap_bytes(seen) + self.2.heap_bytes(seen)
231    }
232}
233
234impl<T: HeapBytes> HeapBytes for OnceLock<T> {
235    fn heap_bytes(&self, seen: &mut Seen) -> usize {
236        self.get().map_or(0, |value| value.heap_bytes(seen))
237    }
238}
239
240impl<T: HeapBytes> HeapBytes for Mutex<T> {
241    fn heap_bytes(&self, seen: &mut Seen) -> usize {
242        match self.try_lock() {
243            Ok(value) => value.heap_bytes(seen),
244            Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner().heap_bytes(seen),
245            Err(TryLockError::WouldBlock) => {
246                seen.contend();
247                0
248            }
249        }
250    }
251}
252
253impl<T: HeapBytes> HeapBytes for RwLock<T> {
254    fn heap_bytes(&self, seen: &mut Seen) -> usize {
255        match self.try_read() {
256            Ok(value) => value.heap_bytes(seen),
257            Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner().heap_bytes(seen),
258            Err(TryLockError::WouldBlock) => {
259                seen.contend();
260                0
261            }
262        }
263    }
264}
265
266/// The bytes of the table a hash map or set with `capacity` allocates for
267/// entries of `entry` bytes: the standard library keeps at most seven of
268/// every eight buckets full (a small table one bucket fewer than it has),
269/// and the bucket count is a power of two.
270fn hash_table_bytes(capacity: usize, entry: usize) -> usize {
271    /// Control bytes stored past the last bucket, so a probe can read a
272    /// whole group at any bucket.
273    const GROUP: usize = if cfg!(any(target_arch = "x86", target_arch = "x86_64")) {
274        16
275    } else {
276        8
277    };
278    if capacity == 0 {
279        return 0;
280    }
281    let buckets = if capacity < 8 {
282        (capacity + 1).next_power_of_two()
283    } else {
284        (capacity * 8 / 7).next_power_of_two()
285    };
286    buckets * entry + buckets + GROUP
287}
288
289/// The bytes of the nodes a B-tree of `len` entries of `entry` bytes needs
290/// at the least: one node of eleven slots, with its parent link and
291/// counts, for every eleven entries. For a caller that sizes a map's
292/// entries itself; a map's own [`HeapBytes`] adds this for it.
293#[must_use]
294pub fn btree_bytes(len: usize, entry: usize) -> usize {
295    const SLOTS: usize = 11;
296    const NODE_HEADER: usize = size_of::<usize>() + 2 * size_of::<u16>();
297    len.div_ceil(SLOTS) * (NODE_HEADER + SLOTS * entry)
298}
299
300impl<K: HeapBytes, V: HeapBytes, S> HeapBytes for HashMap<K, V, S> {
301    fn heap_bytes(&self, seen: &mut Seen) -> usize {
302        hash_table_bytes(self.capacity(), size_of::<(K, V)>())
303            + self
304                .iter()
305                .map(|(key, value)| key.heap_bytes(seen) + value.heap_bytes(seen))
306                .sum::<usize>()
307    }
308}
309
310impl<K: HeapBytes, S> HeapBytes for HashSet<K, S> {
311    fn heap_bytes(&self, seen: &mut Seen) -> usize {
312        hash_table_bytes(self.capacity(), size_of::<K>())
313            + self.iter().map(|key| key.heap_bytes(seen)).sum::<usize>()
314    }
315}
316
317impl<K: HeapBytes, V: HeapBytes> HeapBytes for BTreeMap<K, V> {
318    fn heap_bytes(&self, seen: &mut Seen) -> usize {
319        btree_bytes(self.len(), size_of::<K>() + size_of::<V>())
320            + self
321                .iter()
322                .map(|(key, value)| key.heap_bytes(seen) + value.heap_bytes(seen))
323                .sum::<usize>()
324    }
325}
326
327impl<K: HeapBytes> HeapBytes for BTreeSet<K> {
328    fn heap_bytes(&self, seen: &mut Seen) -> usize {
329        btree_bytes(self.len(), size_of::<K>())
330            + self.iter().map(|key| key.heap_bytes(seen)).sum::<usize>()
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    #[test]
339    fn containers_count_their_capacity_and_their_elements() {
340        let mut text = String::with_capacity(40);
341        text.push_str("abc");
342        assert_eq!(heap_bytes_of(&text), 40);
343
344        let strings = vec![String::from("abcd"), String::with_capacity(10)];
345        assert_eq!(
346            heap_bytes_of(&strings),
347            strings.capacity() * size_of::<String>() + 4 + 10
348        );
349
350        let boxed: Box<[u64]> = vec![1, 2, 3].into_boxed_slice();
351        assert_eq!(heap_bytes_of(&boxed), 24);
352        assert_eq!(heap_bytes_of(&Some(String::from("xy"))), 2);
353        assert_eq!(heap_bytes_of(&None::<String>), 0);
354    }
355
356    #[test]
357    fn a_shared_allocation_is_counted_once_per_walk() {
358        let shared = Arc::new(String::from("shared text"));
359        let holders = vec![Arc::clone(&shared), Arc::clone(&shared)];
360        let one = COUNTS + size_of::<String>() + shared.capacity();
361        assert_eq!(
362            heap_bytes_of(&holders),
363            holders.capacity() * size_of::<Arc<String>>() + one
364        );
365        let slice: Arc<[u32]> = Arc::from(vec![1, 2, 3, 4]);
366        assert_eq!(heap_bytes_of(&slice), COUNTS + 16);
367
368        let mut seen = Seen::new();
369        seen.counted_elsewhere(Arc::as_ptr(&shared));
370        assert_eq!(shared.heap_bytes(&mut seen), 0, "counted elsewhere");
371    }
372
373    #[test]
374    fn hash_tables_count_their_buckets_and_control_bytes() {
375        let group = if cfg!(any(target_arch = "x86", target_arch = "x86_64")) {
376            16
377        } else {
378            8
379        };
380        let empty: HashMap<u64, u64> = HashMap::new();
381        assert_eq!(heap_bytes_of(&empty), 0);
382        let mut small: HashMap<u64, u64> = HashMap::new();
383        small.insert(1, 2);
384        // A first insert allocates four buckets, of which three can be full.
385        assert_eq!(small.capacity(), 3);
386        assert_eq!(heap_bytes_of(&small), 4 * 16 + 4 + group);
387        let large: HashSet<u32> = (0..100).collect();
388        let buckets = (large.capacity() * 8 / 7).next_power_of_two();
389        assert_eq!(buckets, 128);
390        assert_eq!(heap_bytes_of(&large), buckets * 4 + buckets + group);
391    }
392
393    #[test]
394    fn btrees_count_full_nodes_and_their_entries() {
395        let empty: BTreeSet<u64> = BTreeSet::new();
396        assert_eq!(heap_bytes_of(&empty), 0);
397        let set: BTreeSet<u64> = (0..12).collect();
398        let node = size_of::<usize>() + 4 + 11 * 8;
399        assert_eq!(heap_bytes_of(&set), 2 * node);
400        let map: BTreeMap<u32, String> = [(1, String::from("abc"))].into();
401        assert_eq!(
402            heap_bytes_of(&map),
403            size_of::<usize>() + 4 + 11 * (4 + size_of::<String>()) + 3
404        );
405    }
406
407    #[test]
408    fn a_held_lock_is_left_out_and_counted() {
409        let locked = Mutex::new(String::from("held"));
410        let _guard = locked.lock();
411        let mut seen = Seen::new();
412        assert_eq!(locked.heap_bytes(&mut seen), 0);
413        assert_eq!(seen.contended(), 1);
414    }
415}