datafusion_execution/memory_pool/peak_recording.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//! Records the peak [`MemoryPool`] reservation reached during a benchmark.
6//!
7//! DataFusion's [`MemoryPool`] deliberately accounts for only the "large"
8//! allocations that scale with input size; intermediate batches flowing between
9//! operators are assumed to be small and are left untracked. The [`MemoryPool`]
10//! documentation therefore advises reserving "some overhead (e.g. 10%)" on top
11//! of the configured limit.
12//!
13//! Nothing reports what that overhead actually is, because the peak reservation
14//! itself is never recorded — [`MemoryPool::reserved`] is a live value that has
15//! usually fallen back to zero by the time a query finishes. This module records
16//! the high-water mark so benchmarks can emit it alongside the peak RSS that
17//! `print_memory_stats` already prints, making the gap between the two
18//! measurable.
19//!
20//! This is measurement only: nothing here enforces a relationship between the
21//! two numbers.
22//!
23//! The same wrapper can also report every reservation change to a
24//! [`MemoryDriftTracker`] (see [`PeakRecordingPool::with_drift_tracker`]),
25//! which compares reservations with the bytes actually allocated.
26//!
27//! What lands in the peak is whatever the pool accounts for, so this follows
28//! the accounting rather than fixing it in place. Arrow-side reservations made
29//! through `ArrowMemoryPool` are included, because that adapter grows a
30//! DataFusion reservation against the pool it wraps; nothing claims buffers
31//! today, but the peak picks it up when something does.
32
33use std::{
34 fmt::{Debug, Display, Formatter},
35 sync::{
36 Arc,
37 atomic::{AtomicUsize, Ordering},
38 },
39};
40
41use super::{
42 MemoryConsumer, MemoryDriftTracker, MemoryLimit, MemoryPool, MemoryReservation,
43};
44use datafusion_common::Result;
45
46/// Wraps a [`MemoryPool`], recording the high-water mark of
47/// [`MemoryPool::reserved`] as reservations come and go.
48///
49/// Every method delegates to the wrapped pool, so wrapping does not change how
50/// memory is granted, limited, or reported. The one thing it does change is
51/// downcasting: `rt.memory_pool.downcast_ref::<FairSpillPool>()` now finds this
52/// wrapper instead of the pool it wraps. Nothing in the benchmarks relies on
53/// that, and [`Self::from_pool`] uses the same mechanism to find the recorder.
54///
55/// Both high-water marks are held per instance, so a benchmark that builds a
56/// fresh runtime per query gets a reading scoped to that query without any
57/// coordination.
58///
59/// # Example
60///
61/// ```
62/// # use std::sync::Arc;
63/// # use datafusion_execution::memory_pool::{GreedyMemoryPool, MemoryConsumer, MemoryPool, PeakRecordingPool};
64/// let recording = Arc::new(PeakRecordingPool::new(Arc::new(GreedyMemoryPool::new(1024))));
65/// let pool: Arc<dyn MemoryPool> = Arc::clone(&recording) as _;
66///
67/// let reservation = MemoryConsumer::new("example").register(&pool);
68/// reservation.try_grow(512)?;
69/// reservation.shrink(512);
70///
71/// // The pool is back to empty, but the high-water mark is retained.
72/// assert_eq!(pool.reserved(), 0);
73/// assert_eq!(recording.peak_reserved(), 512);
74///
75/// // The recorder can also be recovered from the pool it was installed as.
76/// assert_eq!(PeakRecordingPool::from_pool(&*pool).unwrap().peak_reserved(), 512);
77/// # Ok::<(), datafusion_common::DataFusionError>(())
78/// ```
79pub struct PeakRecordingPool {
80 inner: Arc<dyn MemoryPool>,
81 /// Running total of everything granted through this wrapper, kept so the
82 /// peak can be maintained without asking `inner` for its total.
83 reserved: AtomicUsize,
84 /// High-water mark since the last [`PeakRecordingPool::reset_peak`].
85 peak: AtomicUsize,
86 /// High-water mark since this pool was created. Never reset.
87 max: AtomicUsize,
88 /// Tracker every reservation change is reported to, and this pool's label.
89 drift: Option<(Arc<MemoryDriftTracker>, String)>,
90}
91
92impl PeakRecordingPool {
93 /// Wrap `inner`, recording its peak reservation from here on.
94 ///
95 /// `inner` is expected to be empty: the running total starts at zero, so
96 /// anything reserved before wrapping is not counted.
97 pub fn new(inner: Arc<dyn MemoryPool>) -> Self {
98 Self {
99 inner,
100 reserved: AtomicUsize::new(0),
101 peak: AtomicUsize::new(0),
102 max: AtomicUsize::new(0),
103 drift: None,
104 }
105 }
106
107 /// Also report every reservation change to `tracker`. `label` identifies
108 /// this pool in drift log lines, which matters when several pools share
109 /// one tracker.
110 pub fn with_drift_tracker(
111 mut self,
112 tracker: Arc<MemoryDriftTracker>,
113 label: impl Into<String>,
114 ) -> Self {
115 self.drift = Some((tracker, label.into()));
116 self
117 }
118
119 /// The recorder installed as `pool`, if there is one.
120 ///
121 /// Returns `None` whenever a benchmark runs without a memory limit, since
122 /// `CommonOpt::runtime_env_builder` only installs the wrapper alongside a
123 /// pool it has a limit for.
124 pub fn from_pool(pool: &dyn MemoryPool) -> Option<&Self> {
125 pool.downcast_ref::<Self>()
126 }
127
128 /// Peak reservation, in bytes, since the last [`Self::reset_peak`].
129 pub fn peak_reserved(&self) -> usize {
130 self.peak.load(Ordering::Relaxed)
131 }
132
133 /// Peak reservation, in bytes, since this pool was created.
134 ///
135 /// Unlike [`Self::peak_reserved`] this is never reset, so it reports the
136 /// peak across every query that shared this pool.
137 pub fn max_reserved(&self) -> usize {
138 self.max.load(Ordering::Relaxed)
139 }
140
141 /// Reset the value returned by [`Self::peak_reserved`] to what is reserved
142 /// right now, so the next reading covers only what follows.
143 ///
144 /// `BenchmarkRun::start_new_case` calls this, giving each benchmark query
145 /// its own reading. Anything still held when a query starts — data the
146 /// benchmark loaded up front, say — stays in the reading, since the query
147 /// runs with those bytes reserved.
148 pub fn reset_peak(&self) {
149 self.peak
150 .store(self.reserved.load(Ordering::Relaxed), Ordering::Relaxed);
151 }
152
153 /// Add `additional` granted bytes to the running total and publish it to
154 /// both high-water marks.
155 ///
156 /// Accumulating deltas rather than reading [`MemoryPool::reserved`] keeps
157 /// the wrapped pool's own bookkeeping off this path: `FairSpillPool` takes
158 /// its state lock to answer `reserved()`, which would double the lock
159 /// traffic of every accounted allocation in the benchmark being measured.
160 /// The total stays exact because the trait grants exactly what is asked
161 /// for — `grow` is infallible and `try_grow` either grants `additional` or
162 /// returns an error, leaving the reservation untouched.
163 fn record(&self, reservation: &MemoryReservation, additional: usize) {
164 let reserved =
165 self.reserved.fetch_add(additional, Ordering::Relaxed) + additional;
166 self.peak.fetch_max(reserved, Ordering::Relaxed);
167 self.max.fetch_max(reserved, Ordering::Relaxed);
168 if let Some((tracker, label)) = &self.drift {
169 tracker.grew(label, reservation.consumer().name(), additional);
170 }
171 }
172}
173
174impl Debug for PeakRecordingPool {
175 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
176 f.debug_struct("PeakRecordingPool")
177 .field("inner", &self.inner)
178 .field("peak", &self.peak_reserved())
179 .field("max", &self.max_reserved())
180 .field("drift_label", &self.drift.as_ref().map(|(_, label)| label))
181 .finish()
182 }
183}
184
185impl Display for PeakRecordingPool {
186 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
187 // Deferring to the wrapped pool keeps `SHOW ALL`-style output and error
188 // messages identical to running without the wrapper.
189 Display::fmt(&self.inner, f)
190 }
191}
192
193impl MemoryPool for PeakRecordingPool {
194 fn name(&self) -> &str {
195 self.inner.name()
196 }
197
198 fn register(&self, consumer: &MemoryConsumer) {
199 self.inner.register(consumer);
200 }
201
202 fn unregister(&self, consumer: &MemoryConsumer) {
203 self.inner.unregister(consumer);
204 }
205
206 fn grow(&self, reservation: &MemoryReservation, additional: usize) {
207 self.inner.grow(reservation, additional);
208 self.record(reservation, additional);
209 }
210
211 fn shrink(&self, reservation: &MemoryReservation, shrink: usize) {
212 self.inner.shrink(reservation, shrink);
213 self.reserved.fetch_sub(shrink, Ordering::Relaxed);
214 if let Some((tracker, label)) = &self.drift {
215 tracker.shrank(label, reservation.consumer().name(), shrink);
216 }
217 }
218
219 fn try_grow(&self, reservation: &MemoryReservation, additional: usize) -> Result<()> {
220 self.inner.try_grow(reservation, additional)?;
221 self.record(reservation, additional);
222 Ok(())
223 }
224
225 fn reserved(&self) -> usize {
226 self.inner.reserved()
227 }
228
229 fn memory_limit(&self) -> MemoryLimit {
230 self.inner.memory_limit()
231 }
232}
233
234#[cfg(test)]
235mod tests {
236 use crate::memory_pool::GreedyMemoryPool;
237
238 use super::*;
239
240 /// A recording pool over a `GreedyMemoryPool`, returned both as the
241 /// recorder (to read the marks) and as the pool reservations register with.
242 fn pool(limit: usize) -> (Arc<PeakRecordingPool>, Arc<dyn MemoryPool>) {
243 let recording = Arc::new(PeakRecordingPool::new(Arc::new(
244 GreedyMemoryPool::new(limit),
245 )));
246 let pool = Arc::clone(&recording) as Arc<dyn MemoryPool>;
247 (recording, pool)
248 }
249
250 #[test]
251 fn records_high_water_mark_across_reservations() {
252 let (recording, pool) = pool(1024);
253
254 let a = MemoryConsumer::new("a").register(&pool);
255 let b = MemoryConsumer::new("b").register(&pool);
256
257 a.try_grow(300).unwrap();
258 b.try_grow(400).unwrap();
259 // Peak of the sum, not the largest single reservation.
260 assert_eq!(recording.peak_reserved(), 700);
261
262 a.shrink(300);
263 b.try_grow(100).unwrap();
264
265 // Falling back below the peak leaves it untouched, and the later growth
266 // does not reach it.
267 assert_eq!(pool.reserved(), 500);
268 assert_eq!(recording.peak_reserved(), 700);
269 }
270
271 #[test]
272 fn failed_growth_does_not_move_the_peak() {
273 let (recording, pool) = pool(1024);
274
275 let reservation = MemoryConsumer::new("a").register(&pool);
276 reservation.try_grow(600).unwrap();
277 reservation
278 .try_grow(600)
279 .expect_err("should exceed the 1024 byte pool");
280
281 assert_eq!(recording.peak_reserved(), 600);
282 }
283
284 #[test]
285 fn reset_clears_the_window_but_not_the_run_maximum() {
286 let (recording, pool) = pool(1024);
287
288 let reservation = MemoryConsumer::new("a").register(&pool);
289 reservation.try_grow(800).unwrap();
290 reservation.shrink(800);
291
292 recording.reset_peak();
293 assert_eq!(recording.peak_reserved(), 0);
294 assert_eq!(recording.max_reserved(), 800);
295
296 reservation.try_grow(100).unwrap();
297 assert_eq!(recording.peak_reserved(), 100);
298 assert_eq!(recording.max_reserved(), 800);
299 }
300
301 #[test]
302 fn reset_keeps_what_is_still_reserved() {
303 let (recording, pool) = pool(1024);
304
305 // Something a benchmark loaded up front and holds across queries.
306 let held = MemoryConsumer::new("held").register(&pool);
307 held.try_grow(300).unwrap();
308
309 recording.reset_peak();
310 assert_eq!(recording.peak_reserved(), 300);
311
312 let query = MemoryConsumer::new("query").register(&pool);
313 query.try_grow(200).unwrap();
314 assert_eq!(recording.peak_reserved(), 500);
315 }
316
317 #[test]
318 fn marks_are_per_instance() {
319 let (one, one_pool) = pool(1024);
320 let (two, _two_pool) = pool(1024);
321
322 MemoryConsumer::new("a")
323 .register(&one_pool)
324 .try_grow(512)
325 .unwrap();
326
327 assert_eq!(one.peak_reserved(), 512);
328 assert_eq!(two.peak_reserved(), 0);
329 }
330
331 #[test]
332 fn is_recoverable_from_the_pool_it_is_installed_as() {
333 let (recording, pool) = pool(1024);
334
335 MemoryConsumer::new("a")
336 .register(&pool)
337 .try_grow(512)
338 .unwrap();
339
340 let found = PeakRecordingPool::from_pool(&*pool).expect("recorder installed");
341 assert_eq!(found.peak_reserved(), recording.peak_reserved());
342
343 // A pool with no recorder in front of it reports nothing.
344 let plain: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1024));
345 assert!(PeakRecordingPool::from_pool(&*plain).is_none());
346 }
347
348 #[test]
349 fn delegates_limit_and_name_to_the_wrapped_pool() {
350 let inner: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(4096));
351 let wrapped = PeakRecordingPool::new(Arc::clone(&inner));
352
353 assert_eq!(wrapped.name(), inner.name());
354 assert_eq!(wrapped.to_string(), inner.to_string());
355 assert!(matches!(wrapped.memory_limit(), MemoryLimit::Finite(4096)));
356 }
357
358 /// Arrow-side reservations reach the recorder too.
359 ///
360 /// [`ArrowMemoryPool`] implements Arrow's `MemoryPool` by growing a
361 /// DataFusion [`MemoryReservation`] against the pool it wraps, so a buffer
362 /// claimed through it lands in `grow` here. Nothing in DataFusion claims
363 /// buffers yet (see apache/datafusion#22898), but when something does, the
364 /// bytes show up in this peak without further changes — as long as the
365 /// adapter is built from the `RuntimeEnv`'s pool, which is the wrapped one.
366 /// This test pins that.
367 ///
368 /// Only compiled with `--features arrow_buffer_pool`, since that's what
369 /// gates `crate::memory_pool::arrow` and `arrow_buffer::MemoryPool` in the
370 /// first place; not part of this crate's default feature set.
371 #[cfg(feature = "arrow_buffer_pool")]
372 #[test]
373 fn records_reservations_arriving_through_the_arrow_adapter() {
374 use crate::memory_pool::arrow::ArrowMemoryPool;
375 use arrow_buffer::MemoryPool as ArrowMemoryPoolTrait;
376
377 let (recording, pool) = pool(4096);
378
379 let arrow_pool =
380 ArrowMemoryPool::new(Arc::clone(&pool), MemoryConsumer::new("arrow"));
381 let reservation = arrow_pool.reserve(1024);
382
383 // The Arrow-side reservation is visible as DataFusion pool usage...
384 assert_eq!(pool.reserved(), 1024);
385 assert_eq!(recording.peak_reserved(), 1024);
386
387 // ...and dropping it releases the bytes while the peak is retained.
388 drop(reservation);
389 assert_eq!(pool.reserved(), 0);
390 assert_eq!(recording.peak_reserved(), 1024);
391 }
392}