Skip to main content

aft_base/
alloc_trace.rs

1//! Names the operation behind large or bursty heap use in the daemon.
2//!
3//! The `aft` binary installs [`TracingAllocator`] as its global allocator. It
4//! forwards every call to the process allocator and watches two things:
5//!
6//! - One allocation or reallocation of [`LARGE_ALLOCATION_BYTES`] or more
7//!   records an event: its size, the old size for a reallocation, the
8//!   thread, the current operation label and the caller's return addresses.
9//! - Allocations made while an operation label is set (see [`scope`]) add to
10//!   that label's live bytes, and frees made under the same label subtract
11//!   from them. When one label's live bytes cross [`LABEL_BURST_BYTES`] an
12//!   event is recorded, and another when they fall back below half of it.
13//!   A label's count starts again from zero whenever no scope of it is open,
14//!   so memory an operation hands to someone else does not pile up on it
15//!   over the daemon's life.
16//!
17//! The allocator never allocates, locks or logs on behalf of a caller. Its
18//! common path is a thread-local add; every [`FLUSH_QUANTUM_BYTES`] of net
19//! change it adds the thread's share to the label's shared counter with a
20//! relaxed atomic. Events go into a fixed ring that a logger thread drains,
21//! names and writes as WARN lines (see `report`).
22//!
23//! Only Rust heap allocations pass through a global allocator. Memory that C
24//! libraries (SQLite, tree-sitter, ONNX Runtime) take from `malloc` directly
25//! is not seen here.
26
27#[cfg(not(target_os = "linux"))]
28use std::alloc::System as ProcessAllocator;
29use std::alloc::{GlobalAlloc, Layout};
30use std::cell::Cell;
31use std::marker::PhantomData;
32use std::path::Path;
33use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU32, AtomicU64, Ordering};
34use std::sync::Mutex;
35#[cfg(target_os = "linux")]
36use tikv_jemallocator::Jemalloc as ProcessAllocator;
37
38mod capture;
39mod report;
40mod ring;
41
42pub use report::{drain_now, set_line_sink, start_logger};
43
44/// A single allocation at least this large is recorded with its backtrace.
45pub const LARGE_ALLOCATION_BYTES: usize = 64 << 20;
46/// One label's live bytes crossing this records a burst event.
47pub const LABEL_BURST_BYTES: isize = 512 << 20;
48/// A thread hands its pending bytes to the label's shared counter whenever
49/// they move this far from zero, so the shared counter lags each thread by
50/// less than this.
51pub const FLUSH_QUANTUM_BYTES: isize = 1 << 20;
52
53/// Labels the process can name. Fixed labels take the first ids; tool labels
54/// are interned after them until the table is full, and later tool names
55/// share [`Label::TOOL_OTHER`].
56const MAX_LABELS: usize = 128;
57
58/// An operation the allocator attributes live bytes to.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub struct Label(u8);
61
62const FIXED_LABELS: [&str; 11] = [
63    "",
64    "index_build",
65    "callgraph_start",
66    "callgraph_refresh",
67    "segment_fold",
68    "meaning_fill",
69    "symbol_prewarm",
70    "remote_input_capture",
71    "frame_encode",
72    "census",
73    "tool:other",
74];
75
76/// Labels interned at run time, in id order after the fixed ones. Only label
77/// creation and the logger read it; the allocator never does.
78static INTERNED: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
79
80impl Label {
81    /// No operation: allocations are not attributed.
82    pub const NONE: Label = Label(0);
83    /// A data-layer build of a checkout's indexes.
84    pub const INDEX_BUILD: Label = Label(1);
85    /// Starting a checkout's live call-graph engine.
86    pub const CALLGRAPH_START: Label = Label(2);
87    /// Resolving the call graph again after edits.
88    pub const CALLGRAPH_REFRESH: Label = Label(3);
89    /// Folding a checkout's stored segments into one.
90    pub const SEGMENT_FOLD: Label = Label(4);
91    /// One round of filling the meaning-search vectors.
92    pub const MEANING_FILL: Label = Label(5);
93    /// Warming a checkout's symbol cache after it binds.
94    pub const SYMBOL_PREWARM: Label = Label(6);
95    /// Capturing the inputs of a remote shell job.
96    pub const REMOTE_INPUT_CAPTURE: Label = Label(7);
97    /// Encoding a reply frame for the transport.
98    pub const FRAME_ENCODE: Label = Label(8);
99    /// Measuring the memory census.
100    pub const CENSUS: Label = Label(9);
101    /// A tool call whose name did not fit in the label table.
102    pub const TOOL_OTHER: Label = Label(10);
103
104    /// The label for a call of the tool `name`, as `tool:<name>`.
105    pub fn tool(name: &str) -> Label {
106        let valid = !name.is_empty()
107            && name.len() <= 48
108            && name
109                .bytes()
110                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'));
111        if !valid {
112            return Label::TOOL_OTHER;
113        }
114        Label::intern_with_prefix("tool:", name).unwrap_or(Label::TOOL_OTHER)
115    }
116
117    /// A label with any name, interned like a tool label. For tests and
118    /// probes that need a label no production path uses.
119    #[doc(hidden)]
120    pub fn custom(name: &str) -> Label {
121        Label::intern_with_prefix("", name).unwrap_or(Label::TOOL_OTHER)
122    }
123
124    fn intern_with_prefix(prefix: &str, name: &str) -> Option<Label> {
125        let matches = |entry: &str| entry.strip_prefix(prefix) == Some(name);
126        if let Some(index) = FIXED_LABELS.iter().position(|entry| matches(entry)) {
127            return Some(Label(index as u8));
128        }
129        let mut interned = INTERNED.lock().unwrap_or_else(|e| e.into_inner());
130        let offset = FIXED_LABELS.len();
131        if let Some(index) = interned.iter().position(|entry| matches(entry)) {
132            return Some(Label((offset + index) as u8));
133        }
134        if offset + interned.len() >= MAX_LABELS {
135            return None;
136        }
137        let leaked: &'static str = Box::leak(format!("{prefix}{name}").into_boxed_str());
138        interned.push(leaked);
139        Some(Label((offset + interned.len() - 1) as u8))
140    }
141
142    /// The label's name; empty for [`Label::NONE`].
143    pub fn name(self) -> &'static str {
144        label_name(self.0)
145    }
146}
147
148fn label_name(id: u8) -> &'static str {
149    let id = usize::from(id);
150    if let Some(name) = FIXED_LABELS.get(id) {
151        return name;
152    }
153    INTERNED
154        .lock()
155        .unwrap_or_else(|e| e.into_inner())
156        .get(id - FIXED_LABELS.len())
157        .copied()
158        .unwrap_or("unknown")
159}
160
161/// The repository an operation works on, kept inline so that the allocator
162/// can copy it into an event without allocating: the last component of the
163/// root path, cut to fit.
164#[derive(Clone, Copy)]
165pub struct RootName {
166    len: u8,
167    bytes: [u8; 47],
168}
169
170impl RootName {
171    pub const EMPTY: RootName = RootName {
172        len: 0,
173        bytes: [0; 47],
174    };
175
176    pub fn from_path(root: &Path) -> RootName {
177        let name = root
178            .file_name()
179            .map(|name| name.to_string_lossy())
180            .unwrap_or_else(|| root.to_string_lossy());
181        RootName::from_str(&name)
182    }
183
184    fn from_str(name: &str) -> RootName {
185        let mut end = name.len().min(47);
186        while !name.is_char_boundary(end) {
187            end -= 1;
188        }
189        let mut out = RootName::EMPTY;
190        out.bytes[..end].copy_from_slice(&name.as_bytes()[..end]);
191        out.len = end as u8;
192        out
193    }
194
195    pub fn as_str(&self) -> &str {
196        std::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap_or("")
197    }
198}
199
200/// Shared counters of one label.
201struct LabelState {
202    /// Net bytes allocated minus freed under the label since it was last idle.
203    live: AtomicIsize,
204    /// Highest `live` since the previous census.
205    census_peak: AtomicIsize,
206    /// Highest `live` since it crossed [`LABEL_BURST_BYTES`].
207    burst_peak: AtomicIsize,
208    /// Open scopes of the label, across threads. Carried scopes in pool
209    /// tasks do not count: their owner's scope covers them.
210    active: AtomicU32,
211    /// Whether the label is above the burst threshold, so that a crossing is
212    /// reported once until it falls back.
213    crossed: AtomicBool,
214    /// When the current burst started, in nanoseconds of [`monotonic_ns`].
215    crossed_at_ns: AtomicU64,
216}
217
218impl LabelState {
219    const fn new() -> Self {
220        Self {
221            live: AtomicIsize::new(0),
222            census_peak: AtomicIsize::new(0),
223            burst_peak: AtomicIsize::new(0),
224            active: AtomicU32::new(0),
225            crossed: AtomicBool::new(false),
226            crossed_at_ns: AtomicU64::new(0),
227        }
228    }
229}
230
231static LABELS: [LabelState; MAX_LABELS] = [const { LabelState::new() }; MAX_LABELS];
232
233/// Per-thread tracing state. Every field is a `Cell` with a const initial
234/// value and no destructor, so reading it inside the allocator never
235/// allocates and still works while the thread's other locals are torn down.
236struct ThreadState {
237    /// The label new allocations are attributed to.
238    label: Cell<u8>,
239    /// The label `pending` belongs to. It lags `label` after a scope change
240    /// until the next allocation, which hands the old label its bytes.
241    pending_label: Cell<u8>,
242    /// Net bytes not yet added to `pending_label`'s shared counter.
243    pending: Cell<isize>,
244    /// Set while this thread records an event or runs the logger, so that
245    /// nothing done there is traced again.
246    busy: Cell<bool>,
247    root: Cell<RootName>,
248}
249
250thread_local! {
251    static THREAD: ThreadState = const {
252        ThreadState {
253            label: Cell::new(0),
254            pending_label: Cell::new(0),
255            pending: Cell::new(0),
256            busy: Cell::new(false),
257            root: Cell::new(RootName::EMPTY),
258        }
259    };
260}
261
262/// The global allocator wrapper the `aft` binary installs. It forwards to
263/// jemalloc on Linux and the system allocator elsewhere, then reports each call.
264pub struct TracingAllocator;
265
266unsafe impl GlobalAlloc for TracingAllocator {
267    #[inline]
268    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
269        let ptr = unsafe { ProcessAllocator.alloc(layout) };
270        if !ptr.is_null() {
271            on_alloc(layout.size());
272        }
273        ptr
274    }
275
276    #[inline]
277    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
278        let ptr = unsafe { ProcessAllocator.alloc_zeroed(layout) };
279        if !ptr.is_null() {
280            on_alloc(layout.size());
281        }
282        ptr
283    }
284
285    #[inline]
286    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
287        unsafe { ProcessAllocator.dealloc(ptr, layout) };
288        account(-(layout.size() as isize));
289    }
290
291    #[inline]
292    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
293        let next = unsafe { ProcessAllocator.realloc(ptr, layout, new_size) };
294        if !next.is_null() {
295            if new_size >= LARGE_ALLOCATION_BYTES {
296                record_large(EventKind::Realloc, new_size, layout.size());
297            }
298            account(new_size as isize - layout.size() as isize);
299        }
300        next
301    }
302}
303
304#[inline(always)]
305fn on_alloc(size: usize) {
306    if size >= LARGE_ALLOCATION_BYTES {
307        record_large(EventKind::Alloc, size, 0);
308    }
309    account(size as isize);
310}
311
312/// Adds `delta` to the current label's pending bytes on this thread.
313#[inline(always)]
314fn account(delta: isize) {
315    THREAD.with(|thread| {
316        let label = thread.label.get();
317        if label != thread.pending_label.get() {
318            switch_pending(thread, label, delta);
319            return;
320        }
321        if label == 0 {
322            return;
323        }
324        let pending = thread.pending.get() + delta;
325        if pending >= FLUSH_QUANTUM_BYTES || pending <= -FLUSH_QUANTUM_BYTES {
326            thread.pending.set(0);
327            flush(thread, label, pending);
328        } else {
329            thread.pending.set(pending);
330        }
331    });
332}
333
334/// The thread's label changed since its last allocation: hand the old label
335/// what it is owed and start counting for the new one.
336#[cold]
337fn switch_pending(thread: &ThreadState, label: u8, delta: isize) {
338    let old = thread.pending_label.get();
339    let owed = thread.pending.replace(0);
340    if old != 0 && owed != 0 {
341        flush(thread, old, owed);
342    }
343    thread.pending_label.set(label);
344    if label == 0 {
345        return;
346    }
347    if delta >= FLUSH_QUANTUM_BYTES || delta <= -FLUSH_QUANTUM_BYTES {
348        flush(thread, label, delta);
349    } else {
350        thread.pending.set(delta);
351    }
352}
353
354/// Adds `delta` to `label`'s shared counter and records a burst crossing or
355/// its end.
356#[cold]
357fn flush(thread: &ThreadState, label: u8, delta: isize) {
358    let state = &LABELS[usize::from(label)];
359    let live = state.live.fetch_add(delta, Ordering::Relaxed) + delta;
360    if delta > 0 {
361        state.census_peak.fetch_max(live, Ordering::Relaxed);
362        if live >= LABEL_BURST_BYTES {
363            state.burst_peak.fetch_max(live, Ordering::Relaxed);
364            if !state.crossed.load(Ordering::Relaxed)
365                && !state.crossed.swap(true, Ordering::Relaxed)
366            {
367                state.crossed_at_ns.store(monotonic_ns(), Ordering::Relaxed);
368                record_burst(thread, label, live);
369            }
370        }
371    } else if live < LABEL_BURST_BYTES / 2 && state.crossed.load(Ordering::Relaxed) {
372        end_burst(label, thread.root.get());
373    }
374}
375
376/// Records the end of `label`'s burst if this caller is the one to clear it.
377fn end_burst(label: u8, root: RootName) {
378    let state = &LABELS[usize::from(label)];
379    if !state.crossed.swap(false, Ordering::Relaxed) {
380        return;
381    }
382    let peak = state.burst_peak.swap(0, Ordering::Relaxed);
383    let started = state.crossed_at_ns.load(Ordering::Relaxed);
384    let mut event = ring::Event::new(EventKind::BurstEnded);
385    event.label = label;
386    event.root = root;
387    event.size = peak.max(0) as usize;
388    event.old_size = state.live.load(Ordering::Relaxed).max(0) as usize;
389    event.duration_ns = monotonic_ns().saturating_sub(started);
390    ring::push(&mut event);
391}
392
393#[derive(Clone, Copy, Debug, PartialEq, Eq)]
394pub(crate) enum EventKind {
395    Alloc,
396    Realloc,
397    BurstCrossed,
398    BurstEnded,
399}
400
401/// Records one large allocation. Rare, so it may take a backtrace and read
402/// the thread's name, but it still must not allocate.
403#[cold]
404#[inline(never)]
405fn record_large(kind: EventKind, size: usize, old_size: usize) {
406    THREAD.with(|thread| {
407        if thread.busy.replace(true) {
408            return;
409        }
410        let mut event = ring::Event::new(kind);
411        event.size = size;
412        event.old_size = old_size;
413        event.label = thread.label.get();
414        event.root = thread.root.get();
415        capture::fill(&mut event);
416        ring::push(&mut event);
417        thread.busy.set(false);
418    });
419}
420
421#[cold]
422#[inline(never)]
423fn record_burst(thread: &ThreadState, label: u8, live: isize) {
424    if thread.busy.replace(true) {
425        return;
426    }
427    let mut event = ring::Event::new(EventKind::BurstCrossed);
428    event.size = live.max(0) as usize;
429    event.label = label;
430    event.root = thread.root.get();
431    capture::fill(&mut event);
432    ring::push(&mut event);
433    thread.busy.set(false);
434}
435
436fn monotonic_ns() -> u64 {
437    static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
438    let epoch = *EPOCH.get_or_init(std::time::Instant::now);
439    u64::try_from(epoch.elapsed().as_nanos()).unwrap_or(u64::MAX)
440}
441
442/// While alive, allocations on this thread are attributed to its label.
443/// Dropping it restores the label and root that were current before.
444#[must_use = "the label applies only while the guard lives"]
445pub struct ScopeGuard {
446    previous_label: u8,
447    previous_root: RootName,
448    label: u8,
449    /// Whether this scope counts toward the label's open scopes; a carried
450    /// scope in a pool task does not.
451    owner: bool,
452    _not_send: PhantomData<*const ()>,
453}
454
455/// Attributes this thread's allocations to `label` until the guard drops.
456/// With a `root`, events name that repository; without one the current
457/// root, if any, stays.
458pub fn scope(label: Label, root: Option<&Path>) -> ScopeGuard {
459    let root = root.map(RootName::from_path);
460    enter(label.0, root, true)
461}
462
463fn enter(label: u8, root: Option<RootName>, owner: bool) -> ScopeGuard {
464    if owner && label != 0 {
465        LABELS[usize::from(label)]
466            .active
467            .fetch_add(1, Ordering::Relaxed);
468    }
469    THREAD.with(|thread| {
470        let previous_label = thread.label.replace(label);
471        let previous_root = thread.root.get();
472        if let Some(root) = root {
473            thread.root.set(root);
474        }
475        ScopeGuard {
476            previous_label,
477            previous_root,
478            label,
479            owner,
480            _not_send: PhantomData,
481        }
482    })
483}
484
485impl Drop for ScopeGuard {
486    fn drop(&mut self) {
487        let root = THREAD.with(|thread| {
488            let root = thread.root.get();
489            if self.owner && thread.pending_label.get() == self.label {
490                // The label may go idle below; hand it this thread's bytes
491                // first so they are not added after its count restarts.
492                let owed = thread.pending.replace(0);
493                if self.label != 0 && owed != 0 {
494                    flush(thread, self.label, owed);
495                }
496            }
497            thread.label.set(self.previous_label);
498            thread.root.set(self.previous_root);
499            root
500        });
501        if !self.owner || self.label == 0 {
502            return;
503        }
504        close_scope(self.label, root);
505    }
506}
507
508/// The current thread's label and root, to carry into work handed to a pool.
509#[derive(Clone, Copy)]
510pub struct Carry {
511    label: u8,
512    root: RootName,
513}
514
515/// Captures the current label and root for a pool task; see [`Carry::enter`].
516pub fn carry() -> Carry {
517    THREAD.with(|thread| Carry {
518        label: thread.label.get(),
519        root: thread.root.get(),
520    })
521}
522
523/// `pool.install(op)`, with `op` run under the caller's label. Parallel
524/// iterators inside `op` carry it further with [`Carry::each`].
525pub fn install<R: Send>(pool: &rayon::ThreadPool, op: impl FnOnce() -> R + Send) -> R {
526    pool.install(carry().wrap(op))
527}
528
529/// `inner`, with every poll run under `label`. For async work, where a
530/// [`ScopeGuard`] cannot be held across an await: the label is open from the
531/// first poll until the future is dropped.
532pub fn future<F: std::future::Future>(label: Label, root: Option<&Path>, inner: F) -> Labelled<F> {
533    Labelled {
534        inner,
535        carry: Carry {
536            label: label.0,
537            root: root.map_or_else(|| carry().root, RootName::from_path),
538        },
539        open: false,
540    }
541}
542
543/// A future whose polls run under a label; see [`future`].
544pub struct Labelled<F> {
545    inner: F,
546    carry: Carry,
547    /// Whether this future counts as an open scope of its label.
548    open: bool,
549}
550
551impl<F: std::future::Future> std::future::Future for Labelled<F> {
552    type Output = F::Output;
553
554    fn poll(
555        self: std::pin::Pin<&mut Self>,
556        cx: &mut std::task::Context<'_>,
557    ) -> std::task::Poll<F::Output> {
558        // SAFETY: `inner` is never moved out of the pinned wrapper; the other
559        // fields are plain data.
560        let this = unsafe { self.get_unchecked_mut() };
561        if !this.open && this.carry.label != 0 {
562            this.open = true;
563            LABELS[usize::from(this.carry.label)]
564                .active
565                .fetch_add(1, Ordering::Relaxed);
566        }
567        let _label = this.carry.enter();
568        // SAFETY: as above.
569        unsafe { std::pin::Pin::new_unchecked(&mut this.inner) }.poll(cx)
570    }
571}
572
573impl<F> Drop for Labelled<F> {
574    fn drop(&mut self) {
575        if self.open {
576            close_scope(self.carry.label, self.carry.root);
577        }
578    }
579}
580
581/// One open scope of `label` closed. When it was the last, the label's live
582/// count is reset to zero: no operation of the label is running, so any
583/// bytes still counted are results it returned to other code, and keeping
584/// them would let the count grow over the daemon's life.
585fn close_scope(label: u8, root: RootName) {
586    let state = &LABELS[usize::from(label)];
587    if state.active.fetch_sub(1, Ordering::Relaxed) == 1 {
588        state.live.store(0, Ordering::Relaxed);
589        end_burst(label, root);
590    }
591}
592
593impl Carry {
594    /// Attributes the pool thread's allocations to the carried label until
595    /// the guard drops. The task's owner keeps the label open meanwhile.
596    pub fn enter(&self) -> ScopeGuard {
597        enter(self.label, Some(self.root), false)
598    }
599
600    /// `work`, run under the carried label wherever it runs.
601    pub fn wrap<R>(self, work: impl FnOnce() -> R) -> impl FnOnce() -> R {
602        move || {
603            let _label = self.enter();
604            work()
605        }
606    }
607
608    /// `work` for each item of a parallel iterator, each call run under the
609    /// carried label on whichever pool thread takes the item.
610    pub fn each<T, R>(self, work: impl Fn(T) -> R) -> impl Fn(T) -> R {
611        move |item| {
612            let _label = self.enter();
613            work(item)
614        }
615    }
616
617    pub fn label(&self) -> Label {
618        Label(self.label)
619    }
620}
621
622/// One label's high-water mark for the memory census.
623#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq)]
624pub struct LabelPeak {
625    pub label: &'static str,
626    /// Highest live bytes since the previous census.
627    pub peak_bytes: u64,
628    /// Live bytes now.
629    pub live_bytes: u64,
630}
631
632/// The `limit` labels with the highest live bytes since the previous call,
633/// highest first; each label's mark then restarts from its current count.
634/// Labels that never held a byte are left out. Empty unless the logger runs,
635/// which only the `aft` binary starts: without the tracer installed nothing
636/// counts real allocations, and unit tests that drive the hooks by hand must
637/// not leak their labels into other tests' census.
638pub fn take_census_peaks(limit: usize) -> Vec<LabelPeak> {
639    if !report::logger_started() {
640        return Vec::new();
641    }
642    collect_census_peaks(limit)
643}
644
645fn collect_census_peaks(limit: usize) -> Vec<LabelPeak> {
646    let mut peaks = Vec::new();
647    for (id, state) in LABELS.iter().enumerate().skip(1) {
648        let live = state.live.load(Ordering::Relaxed).max(0);
649        let peak = state.census_peak.swap(live, Ordering::Relaxed).max(live);
650        if peak > 0 {
651            peaks.push((id as u8, peak as u64, live as u64));
652        }
653    }
654    peaks.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
655    peaks.truncate(limit);
656    peaks
657        .into_iter()
658        .map(|(id, peak_bytes, live_bytes)| LabelPeak {
659            label: label_name(id),
660            peak_bytes,
661            live_bytes,
662        })
663        .collect()
664}
665
666/// Live bytes attributed to `label` right now, including this thread's
667/// pending share.
668#[doc(hidden)]
669pub fn live_bytes(label: Label) -> isize {
670    let pending = THREAD.with(|thread| {
671        if thread.pending_label.get() == label.0 {
672            thread.pending.get()
673        } else {
674            0
675        }
676    });
677    LABELS[usize::from(label.0)].live.load(Ordering::Relaxed) + pending
678}
679
680#[cfg(test)]
681mod tests;