datafusion_execution/memory_pool/mod.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//! [`MemoryPool`] for memory management during query execution, [`proxy`] for
6//! help with allocation accounting.
7
8use datafusion_common::{Result, internal_datafusion_err};
9use std::any::Any;
10use std::fmt::Display;
11use std::hash::{Hash, Hasher};
12use std::{cmp::Ordering, sync::Arc, sync::atomic};
13
14mod drift;
15mod merge_memory_pool;
16mod peak_recording;
17mod pool;
18
19#[cfg(feature = "arrow_buffer_pool")]
20pub mod arrow;
21
22pub mod proxy {
23 pub use datafusion_common::utils::proxy::{HashTableAllocExt, VecAllocExt};
24}
25
26pub use datafusion_common::{
27 human_readable_count, human_readable_duration, human_readable_size, units,
28};
29pub use drift::*;
30pub use merge_memory_pool::{MergeMemoryPool, WorkspaceLoan};
31pub use peak_recording::*;
32pub use pool::*;
33
34/// Tracks and potentially limits memory use across operators during execution.
35///
36/// # Memory Management Overview
37///
38/// DataFusion is a streaming query engine, processing most queries without
39/// buffering the entire input. Most operators require a fixed amount of memory
40/// based on the schema and target batch size. However, certain operations such
41/// as sorting and grouping/joining, require buffering intermediate results,
42/// which can require memory proportional to the number of input rows.
43///
44/// Rather than tracking all allocations, DataFusion takes a pragmatic approach:
45/// Intermediate memory used as data streams through the system is not accounted
46/// (it assumed to be "small") but the large consumers of memory must register
47/// and constrain their use. This design trades off the additional code
48/// complexity of memory tracking with limiting resource usage.
49///
50/// When limiting memory with a `MemoryPool` you should typically reserve some
51/// overhead (e.g. 10%) for the "small" memory allocations that are not tracked.
52///
53/// # Memory Management Design
54///
55/// As explained above, DataFusion's design ONLY limits operators that require
56/// "large" amounts of memory (proportional to number of input rows), such as
57/// `GroupByHashExec`. It does NOT track and limit memory used internally by
58/// other operators such as `DataSourceExec` or the `RecordBatch`es that flow
59/// between operators. Furthermore, operators should not reserve memory for the
60/// batches they produce. Instead, if a consumer operator needs to hold batches
61/// from its producers in memory for an extended period, it is the consumer
62/// operator's responsibility to reserve the necessary memory for those batches.
63///
64/// In order to avoid allocating memory until the OS or the container system
65/// kills the process, DataFusion `ExecutionPlan`s (operators) that consume
66/// large amounts of memory must first request their desired allocation from a
67/// [`MemoryPool`] before allocating more. The request is typically managed via
68/// a [`MemoryReservation`] and [`MemoryConsumer`].
69///
70/// If the allocation is successful, the operator should proceed and allocate
71/// the desired memory. If the allocation fails, the operator must either first
72/// free memory (e.g. by spilling to local disk) and try again, or error.
73///
74/// Note that a `MemoryPool` can be shared by concurrently executing plans,
75/// which can be used to control memory usage in a multi-tenant system.
76///
77/// # How MemoryPool works by example
78///
79/// Scenario 1:
80/// For `Filter` operator, `RecordBatch`es will stream through it, so it
81/// don't have to keep track of memory usage through [`MemoryPool`].
82///
83/// Scenario 2:
84/// For `CrossJoin` operator, if the input size gets larger, the intermediate
85/// state will also grow. So `CrossJoin` operator will use [`MemoryPool`] to
86/// limit the memory usage.
87/// 2.1 `CrossJoin` operator has read a new batch, asked memory pool for
88/// additional memory. Memory pool updates the usage and returns success.
89/// 2.2 `CrossJoin` has read another batch, and tries to reserve more memory
90/// again, memory pool does not have enough memory. Since `CrossJoin` operator
91/// has not implemented spilling, it will stop execution and return an error.
92///
93/// Scenario 3:
94/// For `Aggregate` operator, its intermediate states will also accumulate as
95/// the input size gets larger, but with spilling capability. When it tries to
96/// reserve more memory from the memory pool, and the memory pool has already
97/// reached the memory limit, it will return an error. Then, `Aggregate`
98/// operator will spill the intermediate buffers to disk, and release memory
99/// from the memory pool, and continue to retry memory reservation.
100///
101/// # Related Structs
102///
103/// To better understand memory management in DataFusion, here are the key structs
104/// and their relationships:
105///
106/// - [`MemoryConsumer`]: A named allocation traced by a particular operator. If an
107/// execution is parallelized, and there are multiple partitions of the same
108/// operator, each partition will have a separate `MemoryConsumer`.
109/// - `SharedRegistration`: A registration of a `MemoryConsumer` with a `MemoryPool`.
110/// `SharedRegistration` and `MemoryPool` have a many-to-one relationship. `MemoryPool`
111/// implementation can decide how to allocate memory based on the registered consumers.
112/// (e.g. `FairSpillPool` will try to share available memory evenly among all registered
113/// consumers)
114/// - [`MemoryReservation`]: Each `MemoryConsumer`/operator can have multiple
115/// `MemoryReservation`s for different internal data structures. The relationship
116/// between `MemoryConsumer` and `MemoryReservation` is one-to-many. This design
117/// enables cleaner operator implementations:
118/// - Different `MemoryReservation`s can be used for different purposes
119/// - `MemoryReservation` follows RAII principles - to release a reservation,
120/// simply drop the `MemoryReservation` object. When all `MemoryReservation`s
121/// for a `SharedRegistration` are dropped, the `SharedRegistration` is dropped
122/// when its reference count reaches zero, automatically unregistering the
123/// `MemoryConsumer` from the `MemoryPool`.
124///
125/// ## Relationship Diagram
126///
127/// ```text
128/// ┌──────────────────┐ ┌──────────────────┐
129/// │MemoryReservation │ │MemoryReservation │
130/// └───┬──────────────┘ └──────────────────┘ ......
131/// │belongs to │
132/// │ ┌───────────────────────┘ │ │
133/// │ │ │ │
134/// ▼ ▼ ▼ ▼
135/// ┌────────────────────────┐ ┌────────────────────────┐
136/// │ SharedRegistration │ │ SharedRegistration │
137/// │ ┌────────────────┐ │ │ ┌────────────────┐ │
138/// │ │ │ │ │ │ │ │
139/// │ │ MemoryConsumer │ │ │ │ MemoryConsumer │ │
140/// │ │ │ │ │ │ │ │
141/// │ └────────────────┘ │ │ └────────────────┘ │
142/// └────────────┬───────────┘ └────────────┬───────────┘
143/// │ │
144/// │ register│into
145/// │ │
146/// └─────────────┐ ┌──────────────┘
147/// │ │
148/// ▼ ▼
149/// ╔═══════════════════════════════════════════════════╗
150/// ║ ║
151/// ║ MemoryPool ║
152/// ║ ║
153/// ╚═══════════════════════════════════════════════════╝
154/// ```
155///
156/// For example, there are two parallel partitions of an operator X: each partition
157/// corresponds to a `MemoryConsumer` in the above diagram. Inside each partition of
158/// operator X, there are typically several `MemoryReservation`s - one for each
159/// internal data structure that needs memory tracking (e.g., 1 reservation for the hash
160/// table, and 1 reservation for buffered input, etc.).
161///
162/// # Implementing `MemoryPool`
163///
164/// You can implement a custom allocation policy by implementing the
165/// [`MemoryPool`] trait and configuring a `SessionContext` appropriately.
166/// However, DataFusion comes with the following simple memory pool implementations that
167/// handle many common cases:
168///
169/// * [`UnboundedMemoryPool`]: no memory limits (the default)
170///
171/// * [`GreedyMemoryPool`]: Limits memory usage to a fixed size using a "first
172/// come first served" policy
173///
174/// * [`FairSpillPool`]: Limits memory usage to a fixed size, allocating memory
175/// to all spilling operators fairly
176///
177/// * [`TrackConsumersPool`]: Wraps another [`MemoryPool`] and tracks consumers,
178/// providing better error messages on the largest memory users.
179///
180/// * [`MergeMemoryPool`]: Shares retained workspace across child reservations and
181/// temporary loans, charging a single consumer in its parent pool.
182pub trait MemoryPool: Any + Send + Sync + std::fmt::Debug + Display {
183 /// Return pool name
184 fn name(&self) -> &str;
185
186 /// Registers a new [`MemoryConsumer`]
187 ///
188 /// Note: Subsequent calls to [`Self::grow`] must be made to reserve memory
189 fn register(&self, _consumer: &MemoryConsumer) {}
190
191 /// Records the destruction of a [`MemoryReservation`] with [`MemoryConsumer`]
192 ///
193 /// Note: Prior calls to [`Self::shrink`] must be made to free any reserved memory
194 fn unregister(&self, _consumer: &MemoryConsumer) {}
195
196 /// Infallibly grow the provided `reservation` by `additional` bytes
197 ///
198 /// This must always succeed
199 fn grow(&self, reservation: &MemoryReservation, additional: usize);
200
201 /// Infallibly shrink the provided `reservation` by `shrink` bytes
202 fn shrink(&self, reservation: &MemoryReservation, shrink: usize);
203
204 /// Attempt to grow the provided `reservation` by `additional` bytes
205 ///
206 /// On error the `allocation` will not be increased in size
207 fn try_grow(&self, reservation: &MemoryReservation, additional: usize) -> Result<()>;
208
209 /// Return the total amount of memory reserved
210 fn reserved(&self) -> usize;
211
212 /// Return the memory limit of the pool
213 ///
214 /// The default implementation of `MemoryPool::memory_limit`
215 /// will return `MemoryLimit::Unknown`.
216 /// If you are using your custom memory pool, but have the requirement to
217 /// know the memory usage limit of the pool, please implement this method
218 /// to return it(`Memory::Finite(limit)`).
219 fn memory_limit(&self) -> MemoryLimit {
220 MemoryLimit::Unknown
221 }
222}
223
224impl dyn MemoryPool {
225 /// Returns `true` if this pool is of type `T`.
226 pub fn is<T: MemoryPool>(&self) -> bool {
227 (self as &dyn Any).is::<T>()
228 }
229
230 /// Attempts to downcast this pool to a concrete type `T`.
231 pub fn downcast_ref<T: MemoryPool>(&self) -> Option<&T> {
232 (self as &dyn Any).downcast_ref()
233 }
234}
235
236/// Memory limit of `MemoryPool`
237pub enum MemoryLimit {
238 Infinite,
239 /// Bounded memory limit in bytes.
240 Finite(usize),
241 Unknown,
242}
243
244/// A memory consumer is a named allocation traced by a particular
245/// [`MemoryReservation`] in a [`MemoryPool`]. All allocations are registered to
246/// a particular `MemoryConsumer`;
247///
248/// Each `MemoryConsumer` is identifiable by a process-unique id, and is therefore not cloneable,
249/// If you want a clone of a `MemoryConsumer`, you should look into [`MemoryConsumer::clone_with_new_id`],
250/// but note that this `MemoryConsumer` may be treated as a separate entity based on the used pool,
251/// and is only guaranteed to share the name and inner properties.
252///
253/// For help with allocation accounting, see the [`proxy`] module.
254///
255/// [proxy]: datafusion_common::utils::proxy
256#[derive(Debug)]
257pub struct MemoryConsumer {
258 name: String,
259 can_spill: bool,
260 id: usize,
261}
262
263impl PartialEq for MemoryConsumer {
264 fn eq(&self, other: &Self) -> bool {
265 let is_same_id = self.id == other.id;
266
267 #[cfg(debug_assertions)]
268 if is_same_id {
269 assert_eq!(self.name, other.name);
270 assert_eq!(self.can_spill, other.can_spill);
271 }
272
273 is_same_id
274 }
275}
276
277impl Eq for MemoryConsumer {}
278
279impl Hash for MemoryConsumer {
280 fn hash<H: Hasher>(&self, state: &mut H) {
281 self.id.hash(state);
282 self.name.hash(state);
283 self.can_spill.hash(state);
284 }
285}
286
287impl MemoryConsumer {
288 fn new_unique_id() -> usize {
289 static ID: atomic::AtomicUsize = atomic::AtomicUsize::new(0);
290 ID.fetch_add(1, atomic::Ordering::Relaxed)
291 }
292
293 /// Create a new empty [`MemoryConsumer`] that can be grown using [`MemoryReservation`]
294 pub fn new(name: impl Into<String>) -> Self {
295 Self {
296 name: name.into(),
297 can_spill: false,
298 id: Self::new_unique_id(),
299 }
300 }
301
302 /// Returns a clone of this [`MemoryConsumer`] with a new unique id,
303 /// which can be registered with a [`MemoryPool`],
304 /// This new consumer is separate from the original.
305 pub fn clone_with_new_id(&self) -> Self {
306 Self {
307 name: self.name.clone(),
308 can_spill: self.can_spill,
309 id: Self::new_unique_id(),
310 }
311 }
312
313 /// Return the unique id of this [`MemoryConsumer`]
314 pub fn id(&self) -> usize {
315 self.id
316 }
317
318 /// Set whether this allocation can be spilled to disk
319 pub fn with_can_spill(self, can_spill: bool) -> Self {
320 Self { can_spill, ..self }
321 }
322
323 /// Returns true if this allocation can spill to disk
324 pub fn can_spill(&self) -> bool {
325 self.can_spill
326 }
327
328 /// Returns the name associated with this allocation
329 pub fn name(&self) -> &str {
330 &self.name
331 }
332
333 /// Registers this [`MemoryConsumer`] with the provided [`MemoryPool`] returning
334 /// a [`MemoryReservation`] that can be used to grow or shrink the memory reservation
335 pub fn register(self, pool: &Arc<dyn MemoryPool>) -> MemoryReservation {
336 pool.register(&self);
337 MemoryReservation {
338 registration: Arc::new(SharedRegistration {
339 pool: Arc::clone(pool),
340 consumer: self,
341 }),
342 size: atomic::AtomicUsize::new(0),
343 }
344 }
345}
346
347/// A registration of a [`MemoryConsumer`] with a [`MemoryPool`].
348///
349/// Calls [`MemoryPool::unregister`] on drop to return any memory to
350/// the underlying pool.
351#[derive(Debug)]
352struct SharedRegistration {
353 pool: Arc<dyn MemoryPool>,
354 consumer: MemoryConsumer,
355}
356
357impl Drop for SharedRegistration {
358 fn drop(&mut self) {
359 self.pool.unregister(&self.consumer);
360 }
361}
362
363/// A [`MemoryReservation`] tracks an individual reservation of a
364/// number of bytes of memory in a [`MemoryPool`] that is freed back
365/// to the pool on drop.
366///
367/// The reservation can be grown or shrunk over time.
368#[derive(Debug)]
369pub struct MemoryReservation {
370 registration: Arc<SharedRegistration>,
371 size: atomic::AtomicUsize,
372}
373
374impl MemoryReservation {
375 /// Returns the size of this reservation in bytes
376 pub fn size(&self) -> usize {
377 self.size.load(atomic::Ordering::Relaxed)
378 }
379
380 /// Returns [MemoryConsumer] for this [MemoryReservation]
381 pub fn consumer(&self) -> &MemoryConsumer {
382 &self.registration.consumer
383 }
384
385 /// Frees all bytes from this reservation back to the underlying
386 /// pool, returning the number of bytes freed.
387 pub fn free(&self) -> usize {
388 let size = self.size.swap(0, atomic::Ordering::Relaxed);
389 if size != 0 {
390 self.registration.pool.shrink(self, size);
391 }
392 size
393 }
394
395 /// Frees `capacity` bytes from this reservation
396 ///
397 /// # Panics
398 ///
399 /// Panics if `capacity` exceeds [`Self::size`]
400 pub fn shrink(&self, capacity: usize) {
401 self.size
402 .try_update(
403 atomic::Ordering::Relaxed,
404 atomic::Ordering::Relaxed,
405 |prev| prev.checked_sub(capacity),
406 )
407 .unwrap_or_else(|prev| {
408 panic!("Cannot free the capacity {capacity} out of allocated size {prev}")
409 });
410 self.registration.pool.shrink(self, capacity);
411 }
412
413 /// Tries to free `capacity` bytes from this reservation
414 /// if `capacity` does not exceed [`Self::size`].
415 /// Returns new reservation size,
416 /// or error if shrinking capacity is more than allocated size.
417 pub fn try_shrink(&self, capacity: usize) -> Result<usize> {
418 let prev = self
419 .size
420 .try_update(
421 atomic::Ordering::Relaxed,
422 atomic::Ordering::Relaxed,
423 |prev| prev.checked_sub(capacity),
424 )
425 .map_err(|prev| {
426 internal_datafusion_err!(
427 "Cannot free the capacity {capacity} out of allocated size {prev}"
428 )
429 })?;
430
431 self.registration.pool.shrink(self, capacity);
432 Ok(prev - capacity)
433 }
434
435 /// Sets the size of this reservation to `capacity`
436 pub fn resize(&self, capacity: usize) {
437 let size = self.size.load(atomic::Ordering::Relaxed);
438 match capacity.cmp(&size) {
439 Ordering::Greater => self.grow(capacity - size),
440 Ordering::Less => self.shrink(size - capacity),
441 _ => {}
442 }
443 }
444
445 /// Try to set the size of this reservation to `capacity`
446 pub fn try_resize(&self, capacity: usize) -> Result<()> {
447 let size = self.size.load(atomic::Ordering::Relaxed);
448 match capacity.cmp(&size) {
449 Ordering::Greater => self.try_grow(capacity - size)?,
450 Ordering::Less => {
451 self.try_shrink(size - capacity)?;
452 }
453 _ => {}
454 }
455 Ok(())
456 }
457
458 /// Increase the size of this reservation by `capacity` bytes
459 pub fn grow(&self, capacity: usize) {
460 self.registration.pool.grow(self, capacity);
461 self.size.fetch_add(capacity, atomic::Ordering::Relaxed);
462 }
463
464 /// Try to increase the size of this reservation by `capacity`
465 /// bytes, returning error if there is insufficient capacity left
466 /// in the pool.
467 pub fn try_grow(&self, capacity: usize) -> Result<()> {
468 self.registration.pool.try_grow(self, capacity)?;
469 self.size.fetch_add(capacity, atomic::Ordering::Relaxed);
470 Ok(())
471 }
472
473 /// Splits off `capacity` bytes from this [`MemoryReservation`]
474 /// into a new [`MemoryReservation`] with the same
475 /// [`MemoryConsumer`].
476 ///
477 /// This can be useful to free part of this reservation with RAAI
478 /// style dropping
479 ///
480 /// # Panics
481 ///
482 /// Panics if `capacity` exceeds [`Self::size`]
483 pub fn split(&self, capacity: usize) -> MemoryReservation {
484 self.size
485 .try_update(
486 atomic::Ordering::Relaxed,
487 atomic::Ordering::Relaxed,
488 |prev| prev.checked_sub(capacity),
489 )
490 .unwrap();
491 Self {
492 size: atomic::AtomicUsize::new(capacity),
493 registration: Arc::clone(&self.registration),
494 }
495 }
496
497 /// Returns a new empty [`MemoryReservation`] with the same [`MemoryConsumer`]
498 pub fn new_empty(&self) -> Self {
499 Self {
500 size: atomic::AtomicUsize::new(0),
501 registration: Arc::clone(&self.registration),
502 }
503 }
504
505 /// Splits off all the bytes from this [`MemoryReservation`] into
506 /// a new [`MemoryReservation`] with the same [`MemoryConsumer`]
507 pub fn take(&mut self) -> MemoryReservation {
508 self.split(self.size.load(atomic::Ordering::Relaxed))
509 }
510}
511
512impl Drop for MemoryReservation {
513 fn drop(&mut self) {
514 self.free();
515 }
516}
517
518#[cfg(test)]
519mod tests {
520 use super::*;
521
522 #[test]
523 fn test_id_uniqueness() {
524 let mut ids = std::collections::HashSet::new();
525 for _ in 0..100 {
526 let consumer = MemoryConsumer::new("test");
527 assert!(ids.insert(consumer.id())); // Ensures unique insertion
528 }
529 }
530
531 #[test]
532 fn test_memory_pool_underflow() {
533 let pool = Arc::new(GreedyMemoryPool::new(50)) as _;
534 let a1 = MemoryConsumer::new("a1").register(&pool);
535 assert_eq!(pool.reserved(), 0);
536
537 a1.grow(100);
538 assert_eq!(pool.reserved(), 100);
539
540 assert_eq!(a1.free(), 100);
541 assert_eq!(pool.reserved(), 0);
542
543 a1.try_grow(100).unwrap_err();
544 assert_eq!(pool.reserved(), 0);
545
546 a1.try_grow(30).unwrap();
547 assert_eq!(pool.reserved(), 30);
548
549 let a2 = MemoryConsumer::new("a2").register(&pool);
550 a2.try_grow(25).unwrap_err();
551 assert_eq!(pool.reserved(), 30);
552
553 drop(a1);
554 assert_eq!(pool.reserved(), 0);
555
556 a2.try_grow(25).unwrap();
557 assert_eq!(pool.reserved(), 25);
558 }
559
560 #[test]
561 fn test_split() {
562 let pool = Arc::new(GreedyMemoryPool::new(50)) as _;
563 let r1 = MemoryConsumer::new("r1").register(&pool);
564
565 r1.try_grow(20).unwrap();
566 assert_eq!(r1.size(), 20);
567 assert_eq!(pool.reserved(), 20);
568
569 // take 5 from r1, should still have same reservation split
570 let r2 = r1.split(5);
571 assert_eq!(r1.size(), 15);
572 assert_eq!(r2.size(), 5);
573 assert_eq!(pool.reserved(), 20);
574
575 // dropping r1 frees 15 but retains 5 as they have the same consumer
576 drop(r1);
577 assert_eq!(r2.size(), 5);
578 assert_eq!(pool.reserved(), 5);
579 }
580
581 #[test]
582 fn test_new_empty() {
583 let pool = Arc::new(GreedyMemoryPool::new(50)) as _;
584 let r1 = MemoryConsumer::new("r1").register(&pool);
585
586 r1.try_grow(20).unwrap();
587 let r2 = r1.new_empty();
588 r2.try_grow(5).unwrap();
589
590 assert_eq!(r1.size(), 20);
591 assert_eq!(r2.size(), 5);
592 assert_eq!(pool.reserved(), 25);
593 }
594
595 #[test]
596 fn test_take() {
597 let pool = Arc::new(GreedyMemoryPool::new(50)) as _;
598 let mut r1 = MemoryConsumer::new("r1").register(&pool);
599
600 r1.try_grow(20).unwrap();
601 let r2 = r1.take();
602 r2.try_grow(5).unwrap();
603
604 assert_eq!(r1.size(), 0);
605 assert_eq!(r2.size(), 25);
606 assert_eq!(pool.reserved(), 25);
607
608 // r1 can still grow again
609 r1.try_grow(3).unwrap();
610 assert_eq!(r1.size(), 3);
611 assert_eq!(r2.size(), 25);
612 assert_eq!(pool.reserved(), 28);
613 }
614
615 #[test]
616 fn test_downcast() {
617 let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(50));
618
619 assert!(pool.is::<GreedyMemoryPool>());
620 assert!(!pool.is::<UnboundedMemoryPool>());
621
622 let greedy: &GreedyMemoryPool = pool.downcast_ref().unwrap();
623 assert_eq!(greedy.reserved(), 0);
624 assert!(pool.downcast_ref::<UnboundedMemoryPool>().is_none());
625 }
626
627 #[test]
628 fn test_try_shrink() {
629 let pool = Arc::new(GreedyMemoryPool::new(100)) as _;
630 let r1 = MemoryConsumer::new("r1").register(&pool);
631
632 r1.try_grow(50).unwrap();
633 assert_eq!(r1.size(), 50);
634 assert_eq!(pool.reserved(), 50);
635
636 // Successful shrink returns new size and frees pool memory
637 let new_size = r1.try_shrink(30).unwrap();
638 assert_eq!(new_size, 20);
639 assert_eq!(r1.size(), 20);
640 assert_eq!(pool.reserved(), 20);
641
642 // Freed pool memory is now available to other consumers
643 let r2 = MemoryConsumer::new("r2").register(&pool);
644 r2.try_grow(80).unwrap();
645 assert_eq!(pool.reserved(), 100);
646
647 // Shrinking more than allocated fails without changing state
648 let err = r1.try_shrink(25);
649 assert!(err.is_err());
650 assert_eq!(r1.size(), 20);
651 assert_eq!(pool.reserved(), 100);
652
653 // Shrink to exactly zero
654 let new_size = r1.try_shrink(20).unwrap();
655 assert_eq!(new_size, 0);
656 assert_eq!(r1.size(), 0);
657 assert_eq!(pool.reserved(), 80);
658 }
659}