Skip to main content

datafusion_execution/memory_pool/
drift.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Logs the drift between what [`MemoryPool`]s have reserved and what the
6//! process has actually allocated.
7//!
8//! [`MemoryPool`] accounting is voluntary: only allocations that an operator
9//! explicitly reserves are counted. Anything else (in-flight batches, kernel
10//! scratch space, untracked buffers) is invisible to the pool, so a process
11//! can run out of memory while its pool reports plenty of headroom. See
12//! <https://github.com/apache/datafusion/issues/25650>.
13//!
14//! This module only observes. Nothing here changes how memory is granted or
15//! limited; it logs the gap so that operators which under-report can be found.
16//!
17//! DataFusion is a library and does not choose the global allocator, so the
18//! allocated byte count is supplied by the caller, e.g. from a counting
19//! [`GlobalAlloc`](std::alloc::GlobalAlloc) wrapper or allocator statistics.
20//!
21//! [`MemoryPool`]: super::MemoryPool
22
23use std::{
24    fmt::{Debug, Display, Formatter},
25    sync::{
26        Arc,
27        atomic::{AtomicIsize, AtomicUsize, Ordering},
28    },
29};
30
31use datafusion_common::human_readable_size;
32use parking_lot::Mutex;
33
34/// Returns the number of bytes currently allocated by the process.
35///
36/// This is called on every reservation change (`grow`, `try_grow` and
37/// `shrink`) of every pool that reports to the tracker, so it must be cheap,
38/// e.g. a single atomic load. Do not read allocator statistics that need a
39/// refresh on each call (such as jemalloc's `epoch`).
40pub type AllocatedBytesFn = Arc<dyn Fn() -> usize + Send + Sync>;
41
42/// Default rise in drift, in bytes, needed before another line is logged.
43pub const DEFAULT_DRIFT_LOG_THRESHOLD: usize = 64 * 1024 * 1024;
44
45/// Compares allocated bytes against the total reserved by every pool that
46/// reports to it (see [`PeakRecordingPool::with_drift_tracker`]).
47///
48/// [`PeakRecordingPool::with_drift_tracker`]: super::PeakRecordingPool::with_drift_tracker
49///
50/// A single tracker can be shared by many pools, e.g. one pool per
51/// `SessionContext` in a process running several at once. The reserved total
52/// is then summed across all of them, which is what has to be compared with a
53/// process-wide allocated byte count.
54///
55/// Drift is `allocated - reserved`. A line is logged at `info` level each time
56/// drift rises by at least the log threshold, naming the pool and consumer
57/// whose reservation change triggered the check.
58///
59/// # Example
60///
61/// ```
62/// # use std::sync::Arc;
63/// # use datafusion_execution::memory_pool::{
64/// #     MemoryConsumer, MemoryDriftTracker, MemoryPool, PeakRecordingPool, UnboundedMemoryPool,
65/// # };
66/// // A real caller would read a counting allocator or allocator stats here.
67/// let tracker = Arc::new(MemoryDriftTracker::new(Arc::new(|| 10_000)));
68/// let pool: Arc<dyn MemoryPool> = Arc::new(
69///     PeakRecordingPool::new(Arc::new(UnboundedMemoryPool::default()))
70///         .with_drift_tracker(Arc::clone(&tracker), "example"),
71/// );
72///
73/// let reservation = MemoryConsumer::new("op").register(&pool);
74/// reservation.grow(4_000);
75///
76/// assert_eq!(tracker.reserved(), 4_000);
77/// assert_eq!(tracker.peak_drift().unwrap().drift, 6_000);
78/// ```
79pub struct MemoryDriftTracker {
80    allocated: AllocatedBytesFn,
81    log_threshold: usize,
82    /// Total reserved across every pool reporting to this tracker.
83    reserved: AtomicUsize,
84    /// Positive drift at the time of the last logged line.
85    last_logged: AtomicIsize,
86    /// Largest drift seen.
87    peak_drift: AtomicIsize,
88    /// Where the largest drift was seen.
89    peak: Mutex<Option<DriftSample>>,
90}
91
92/// One observation of drift, recorded by [`MemoryDriftTracker`].
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct DriftSample {
95    /// Label of the pool whose reservation change took this sample, or the source passed to [`MemoryDriftTracker::sample`]. When
96    /// several pools share a tracker, the untracked memory can come from any
97    /// of them.
98    pub pool: String,
99    /// Consumer whose reservation change took this sample (empty for
100    /// [`MemoryDriftTracker::sample`]). This shows when drift was sampled,
101    /// not what caused it.
102    pub consumer: String,
103    /// Bytes reserved across all pools reporting to the tracker.
104    pub reserved: usize,
105    /// Bytes allocated, as reported by the tracker's [`AllocatedBytesFn`].
106    pub allocated: usize,
107    /// `allocated - reserved`.
108    pub drift: isize,
109}
110
111impl Display for DriftSample {
112    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
113        let drift = if self.drift < 0 {
114            format!("-{}", human_readable_size(self.drift.unsigned_abs()))
115        } else {
116            human_readable_size(self.drift as usize)
117        };
118        write!(
119            f,
120            "drift={drift} allocated={} reserved={} pool={} consumer={}",
121            human_readable_size(self.allocated),
122            human_readable_size(self.reserved),
123            self.pool,
124            self.consumer,
125        )
126    }
127}
128
129impl MemoryDriftTracker {
130    /// Create a tracker that reads allocated bytes from `allocated`, logging
131    /// every [`DEFAULT_DRIFT_LOG_THRESHOLD`] of drift.
132    pub fn new(allocated: AllocatedBytesFn) -> Self {
133        Self {
134            allocated,
135            log_threshold: DEFAULT_DRIFT_LOG_THRESHOLD,
136            reserved: AtomicUsize::new(0),
137            last_logged: AtomicIsize::new(0),
138            peak_drift: AtomicIsize::new(isize::MIN),
139            peak: Mutex::new(None),
140        }
141    }
142
143    /// Log a line each time drift rises by `log_threshold` bytes.
144    pub fn with_log_threshold(mut self, log_threshold: usize) -> Self {
145        self.log_threshold = log_threshold;
146        self
147    }
148
149    /// Bytes currently reserved across all pools reporting to this tracker.
150    pub fn reserved(&self) -> usize {
151        self.reserved.load(Ordering::Relaxed)
152    }
153
154    /// The largest drift seen so far, if any reservation has been made.
155    pub fn peak_drift(&self) -> Option<DriftSample> {
156        self.peak.lock().clone()
157    }
158
159    /// Compare the current allocated bytes with the reserved total now,
160    /// without a reservation change.
161    ///
162    /// Drift is otherwise only sampled when a reservation changes, so memory
163    /// allocated by code that reserves little can go unseen until some other
164    /// reservation changes. Calling this periodically, e.g. from a timer,
165    /// closes that gap. `source` is recorded as the pool label.
166    pub fn sample(&self, source: &str) {
167        self.observe(source, "", self.reserved());
168    }
169
170    pub(super) fn grew(&self, pool: &str, consumer: &str, additional: usize) {
171        let reserved =
172            self.reserved.fetch_add(additional, Ordering::Relaxed) + additional;
173        self.observe(pool, consumer, reserved);
174    }
175
176    pub(super) fn shrank(&self, pool: &str, consumer: &str, shrink: usize) {
177        let reserved = self.reserved.fetch_sub(shrink, Ordering::Relaxed) - shrink;
178        self.observe(pool, consumer, reserved);
179    }
180
181    /// Returns `true` if a line was logged.
182    fn observe(&self, pool: &str, consumer: &str, reserved: usize) -> bool {
183        let allocated = (self.allocated)();
184        let drift = allocated as isize - reserved as isize;
185
186        let sample = || DriftSample {
187            pool: pool.to_string(),
188            consumer: consumer.to_string(),
189            reserved,
190            allocated,
191            drift,
192        };
193
194        // Lock-free check first so the lock is only taken for a new peak.
195        if self.peak_drift.fetch_max(drift, Ordering::Relaxed) < drift {
196            let mut peak = self.peak.lock();
197            if peak.as_ref().is_none_or(|p| drift > p.drift) {
198                *peak = Some(sample());
199            }
200        }
201
202        // Only rising positive drift is logged: that is untracked memory, which
203        // is what leads to OOM kills. Negative drift (e.g. an operator
204        // reserving ahead of allocating) counts as zero. Falling drift quietly
205        // lowers the baseline so the next rise is seen.
206        let untracked = drift.max(0);
207        let last = self.last_logged.load(Ordering::Relaxed);
208        let rose = untracked >= last.saturating_add_unsigned(self.log_threshold);
209        if !rose && untracked >= last {
210            return false;
211        }
212        let updated = self
213            .last_logged
214            .compare_exchange(last, untracked, Ordering::Relaxed, Ordering::Relaxed)
215            .is_ok();
216        let logged = updated && rose;
217        if logged {
218            log::info!("memory drift: {}", sample());
219        }
220        logged
221    }
222}
223
224impl Debug for MemoryDriftTracker {
225    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
226        f.debug_struct("MemoryDriftTracker")
227            .field("log_threshold", &self.log_threshold)
228            .field("reserved", &self.reserved())
229            .field("peak", &self.peak_drift())
230            .finish()
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use crate::memory_pool::{
237        MemoryConsumer, MemoryPool, PeakRecordingPool, UnboundedMemoryPool,
238    };
239
240    use super::*;
241
242    /// A tracker whose allocated byte count is set by the test.
243    fn tracker(log_threshold: usize) -> (Arc<AtomicUsize>, Arc<MemoryDriftTracker>) {
244        let allocated = Arc::new(AtomicUsize::new(0));
245        let source = Arc::clone(&allocated);
246        let tracker =
247            MemoryDriftTracker::new(Arc::new(move || source.load(Ordering::Relaxed)))
248                .with_log_threshold(log_threshold);
249        (allocated, Arc::new(tracker))
250    }
251
252    fn pool(tracker: &Arc<MemoryDriftTracker>, label: &str) -> Arc<dyn MemoryPool> {
253        Arc::new(
254            PeakRecordingPool::new(Arc::new(UnboundedMemoryPool::default()))
255                .with_drift_tracker(Arc::clone(tracker), label),
256        )
257    }
258
259    #[test]
260    fn records_peak_drift_and_where_it_happened() {
261        let (allocated, tracker) = tracker(DEFAULT_DRIFT_LOG_THRESHOLD);
262        let pool = pool(&tracker, "q1");
263
264        let a = MemoryConsumer::new("a").register(&pool);
265        let b = MemoryConsumer::new("b").register(&pool);
266
267        allocated.store(1000, Ordering::Relaxed);
268        a.grow(800);
269        allocated.store(5000, Ordering::Relaxed);
270        b.grow(200);
271        allocated.store(1500, Ordering::Relaxed);
272        a.shrink(800);
273
274        assert_eq!(tracker.reserved(), 200);
275        assert_eq!(
276            tracker.peak_drift(),
277            Some(DriftSample {
278                pool: "q1".to_string(),
279                consumer: "b".to_string(),
280                reserved: 1000,
281                allocated: 5000,
282                drift: 4000,
283            })
284        );
285    }
286
287    #[test]
288    fn sums_reservations_across_pools_sharing_a_tracker() {
289        let (allocated, tracker) = tracker(DEFAULT_DRIFT_LOG_THRESHOLD);
290        let one = pool(&tracker, "one");
291        let two = pool(&tracker, "two");
292
293        allocated.store(1000, Ordering::Relaxed);
294        let a = MemoryConsumer::new("a").register(&one);
295        let b = MemoryConsumer::new("b").register(&two);
296        a.grow(300);
297        b.grow(400);
298
299        // Drift is measured against the sum, so the second pool's growth
300        // shrinks it rather than starting from zero.
301        assert_eq!(tracker.reserved(), 700);
302        let peak = tracker.peak_drift().unwrap();
303        assert_eq!(peak.pool, "one");
304        assert_eq!(peak.drift, 700);
305
306        drop(a);
307        drop(b);
308        assert_eq!(tracker.reserved(), 0);
309    }
310
311    #[test]
312    fn drift_can_be_negative() {
313        let (_allocated, tracker) = tracker(DEFAULT_DRIFT_LOG_THRESHOLD);
314        let pool = pool(&tracker, "over-reserved");
315
316        let reservation = MemoryConsumer::new("a").register(&pool);
317        reservation.grow(2048);
318
319        let peak = tracker.peak_drift().unwrap();
320        assert_eq!(peak.drift, -2048);
321        assert_eq!(
322            peak.to_string(),
323            "drift=-2.0 KB allocated=0.0 B reserved=2.0 KB pool=over-reserved consumer=a"
324        );
325    }
326
327    #[test]
328    fn logs_each_rise_by_the_threshold_and_rearms_after_a_fall() {
329        let (allocated, tracker) = tracker(1000);
330        let observe = |bytes: usize, reserved: usize| {
331            allocated.store(bytes, Ordering::Relaxed);
332            tracker.observe("p", "c", reserved)
333        };
334
335        // Negative drift counts as zero, so the baseline stays at zero.
336        assert!(!observe(0, 5000));
337        // Below the threshold: nothing logged.
338        assert!(!observe(999, 0));
339        // Reaching the threshold logs and moves the baseline to 1000.
340        assert!(observe(1000, 0));
341        assert!(!observe(1999, 0));
342        assert!(observe(2000, 0));
343        // Falling drift is not logged but lowers the baseline to 500...
344        assert!(!observe(500, 0));
345        // ...so a rise of the threshold from there logs again.
346        assert!(!observe(1499, 0));
347        assert!(observe(1500, 0));
348    }
349
350    #[test]
351    fn a_threshold_above_isize_max_never_logs() {
352        let (allocated, tracker) = tracker(usize::MAX);
353
354        allocated.store(1 << 40, Ordering::Relaxed);
355        assert!(!tracker.observe("p", "c", 0));
356    }
357
358    #[test]
359    fn sample_observes_without_a_reservation_change() {
360        let (allocated, tracker) = tracker(DEFAULT_DRIFT_LOG_THRESHOLD);
361        let pool = pool(&tracker, "q1");
362        let reservation = MemoryConsumer::new("a").register(&pool);
363        reservation.grow(100);
364
365        allocated.store(5000, Ordering::Relaxed);
366        tracker.sample("timer");
367
368        assert_eq!(
369            tracker.peak_drift(),
370            Some(DriftSample {
371                pool: "timer".to_string(),
372                consumer: String::new(),
373                reserved: 100,
374                allocated: 5000,
375                drift: 4900,
376            })
377        );
378    }
379}