Skip to main content

datafusion_execution/memory_pool/
arrow.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//! Adapter for integrating DataFusion's [`MemoryPool`] with Arrow's memory tracking APIs.
6
7use crate::memory_pool::{MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation};
8use std::fmt::Debug;
9use std::sync::Arc;
10
11/// An adapter that implements Arrow's [`arrow_buffer::MemoryPool`] trait
12/// by wrapping a DataFusion [`MemoryPool`].
13///
14/// This allows DataFusion's memory management system to be used with Arrow's
15/// memory allocation APIs. Each reservation made through this pool will be
16/// tracked using the provided [`MemoryConsumer`], enabling DataFusion to
17/// monitor and limit memory usage across Arrow operations.
18///
19/// This is useful when you want Arrow operations (such as array builders
20/// or compute kernels) to participate in DataFusion's memory management
21/// and respect the same memory limits as DataFusion operators.
22#[derive(Debug)]
23pub struct ArrowMemoryPool {
24    inner: Arc<dyn MemoryPool>,
25    consumer: MemoryConsumer,
26}
27
28impl ArrowMemoryPool {
29    /// Creates a new [`ArrowMemoryPool`] that wraps the given DataFusion [`MemoryPool`]
30    /// and tracks allocations under the specified [`MemoryConsumer`].
31    pub fn new(inner: Arc<dyn MemoryPool>, consumer: MemoryConsumer) -> Self {
32        Self { inner, consumer }
33    }
34}
35
36impl arrow_buffer::MemoryReservation for MemoryReservation {
37    fn size(&self) -> usize {
38        MemoryReservation::size(self)
39    }
40
41    fn resize(&mut self, new_size: usize) {
42        MemoryReservation::resize(self, new_size)
43    }
44}
45
46impl arrow_buffer::MemoryPool for ArrowMemoryPool {
47    fn reserve(&self, size: usize) -> Box<dyn arrow_buffer::MemoryReservation> {
48        let consumer = self.consumer.clone_with_new_id();
49        let reservation = consumer.register(&self.inner);
50        reservation.grow(size);
51
52        Box::new(reservation)
53    }
54
55    fn available(&self) -> isize {
56        // The pool may be overfilled, so this method might return a negative value.
57        (self.capacity() as i128 - self.used() as i128)
58            .try_into()
59            .unwrap_or(isize::MIN)
60    }
61
62    fn used(&self) -> usize {
63        self.inner.reserved()
64    }
65
66    fn capacity(&self) -> usize {
67        match self.inner.memory_limit() {
68            MemoryLimit::Infinite | MemoryLimit::Unknown => usize::MAX,
69            MemoryLimit::Finite(capacity) => capacity,
70        }
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77    use crate::memory_pool::{GreedyMemoryPool, UnboundedMemoryPool};
78    use arrow::array::{Array, Int32Array};
79    use arrow_buffer::MemoryPool;
80
81    // Until https://github.com/apache/arrow-rs/pull/8918 lands, we need to iterate all
82    // buffers in the array. Change once the PR is released.
83    fn claim_array(array: &dyn Array, pool: &dyn MemoryPool) {
84        for buffer in array.to_data().buffers() {
85            buffer.claim(pool);
86        }
87    }
88
89    #[test]
90    pub fn can_claim_array() {
91        let pool = Arc::new(UnboundedMemoryPool::default());
92
93        let consumer = MemoryConsumer::new("arrow");
94        let arrow_pool = ArrowMemoryPool::new(pool, consumer);
95
96        let array = Int32Array::from(vec![1, 2, 3, 4, 5]);
97        claim_array(&array, &arrow_pool);
98
99        assert_eq!(arrow_pool.used(), array.get_buffer_memory_size());
100
101        let slice = array.slice(0, 2);
102
103        // This should be a no-op
104        claim_array(&slice, &arrow_pool);
105
106        assert_eq!(arrow_pool.used(), array.get_buffer_memory_size());
107    }
108
109    #[test]
110    pub fn can_claim_array_with_finite_limit() {
111        let pool_capacity = 1024;
112        let pool = Arc::new(GreedyMemoryPool::new(pool_capacity));
113
114        let consumer = MemoryConsumer::new("arrow");
115        let arrow_pool = ArrowMemoryPool::new(pool, consumer);
116
117        assert_eq!(arrow_pool.capacity(), pool_capacity);
118        assert_eq!(arrow_pool.available(), pool_capacity as isize);
119
120        let array = Int32Array::from(vec![1, 2, 3, 4, 5]);
121        claim_array(&array, &arrow_pool);
122
123        assert_eq!(arrow_pool.used(), array.get_buffer_memory_size());
124        assert_eq!(
125            arrow_pool.available(),
126            (pool_capacity - array.get_buffer_memory_size()) as isize
127        );
128    }
129}