Skip to content

Commit 7815732

Browse files
authored
feat(memory-tracking): implement arrow_buffer::MemoryPool for MemoryPool (apache#18928)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes apache#123` indicates that this PR will close issue apache#123. --> - Closes apache#18926 ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> Related to apache#16841. The ability to correctly account for memory usage of arrow buffers in execution nodes is crucial to maximise resource usage while preventing OOMs. ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> - An implementation of arrow_buffer::MemoryPool for DataFusion's MemoryPool under the `arrow_buffer_pool` feature-flag ## Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> Yes! ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> <!-- If there are any breaking changes to public APIs, please add the `api change` label. --> Introduced new API.
1 parent 9660c98 commit 7815732

File tree

4 files changed

+151
-0
lines changed

4 files changed

+151
-0
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

datafusion/execution/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,14 @@ default = ["sql"]
4646
parquet_encryption = [
4747
"parquet/encryption",
4848
]
49+
arrow_buffer_pool = [
50+
"arrow-buffer/pool",
51+
]
4952
sql = []
5053

5154
[dependencies]
5255
arrow = { workspace = true }
56+
arrow-buffer = { workspace = true }
5357
async-trait = { workspace = true }
5458
chrono = { workspace = true }
5559
dashmap = { workspace = true }
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
//! Adapter for integrating DataFusion's [`MemoryPool`] with Arrow's memory tracking APIs.
19+
20+
use crate::memory_pool::{MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation};
21+
use std::fmt::Debug;
22+
use std::sync::Arc;
23+
24+
/// An adapter that implements Arrow's [`arrow_buffer::MemoryPool`] trait
25+
/// by wrapping a DataFusion [`MemoryPool`].
26+
///
27+
/// This allows DataFusion's memory management system to be used with Arrow's
28+
/// memory allocation APIs. Each reservation made through this pool will be
29+
/// tracked using the provided [`MemoryConsumer`], enabling DataFusion to
30+
/// monitor and limit memory usage across Arrow operations.
31+
///
32+
/// This is useful when you want Arrow operations (such as array builders
33+
/// or compute kernels) to participate in DataFusion's memory management
34+
/// and respect the same memory limits as DataFusion operators.
35+
#[derive(Debug)]
36+
pub struct ArrowMemoryPool {
37+
inner: Arc<dyn MemoryPool>,
38+
consumer: MemoryConsumer,
39+
}
40+
41+
impl ArrowMemoryPool {
42+
/// Creates a new [`ArrowMemoryPool`] that wraps the given DataFusion [`MemoryPool`]
43+
/// and tracks allocations under the specified [`MemoryConsumer`].
44+
pub fn new(inner: Arc<dyn MemoryPool>, consumer: MemoryConsumer) -> Self {
45+
Self { inner, consumer }
46+
}
47+
}
48+
49+
impl arrow_buffer::MemoryReservation for MemoryReservation {
50+
fn size(&self) -> usize {
51+
MemoryReservation::size(self)
52+
}
53+
54+
fn resize(&mut self, new_size: usize) {
55+
MemoryReservation::resize(self, new_size)
56+
}
57+
}
58+
59+
impl arrow_buffer::MemoryPool for ArrowMemoryPool {
60+
fn reserve(&self, size: usize) -> Box<dyn arrow_buffer::MemoryReservation> {
61+
let consumer = self.consumer.clone_with_new_id();
62+
let mut reservation = consumer.register(&self.inner);
63+
reservation.grow(size);
64+
65+
Box::new(reservation)
66+
}
67+
68+
fn available(&self) -> isize {
69+
// The pool may be overfilled, so this method might return a negative value.
70+
(self.capacity() as i128 - self.used() as i128)
71+
.try_into()
72+
.unwrap_or(isize::MIN)
73+
}
74+
75+
fn used(&self) -> usize {
76+
self.inner.reserved()
77+
}
78+
79+
fn capacity(&self) -> usize {
80+
match self.inner.memory_limit() {
81+
MemoryLimit::Infinite | MemoryLimit::Unknown => usize::MAX,
82+
MemoryLimit::Finite(capacity) => capacity,
83+
}
84+
}
85+
}
86+
87+
#[cfg(test)]
88+
mod tests {
89+
use super::*;
90+
use crate::memory_pool::{GreedyMemoryPool, UnboundedMemoryPool};
91+
use arrow::array::{Array, Int32Array};
92+
use arrow_buffer::MemoryPool;
93+
94+
// Until https://github.com/apache/arrow-rs/pull/8918 lands, we need to iterate all
95+
// buffers in the array. Change once the PR is released.
96+
fn claim_array(array: &dyn Array, pool: &dyn MemoryPool) {
97+
for buffer in array.to_data().buffers() {
98+
buffer.claim(pool);
99+
}
100+
}
101+
102+
#[test]
103+
pub fn can_claim_array() {
104+
let pool = Arc::new(UnboundedMemoryPool::default());
105+
106+
let consumer = MemoryConsumer::new("arrow");
107+
let arrow_pool = ArrowMemoryPool::new(pool, consumer);
108+
109+
let array = Int32Array::from(vec![1, 2, 3, 4, 5]);
110+
claim_array(&array, &arrow_pool);
111+
112+
assert_eq!(arrow_pool.used(), array.get_buffer_memory_size());
113+
114+
let slice = array.slice(0, 2);
115+
116+
// This should be a no-op
117+
claim_array(&slice, &arrow_pool);
118+
119+
assert_eq!(arrow_pool.used(), array.get_buffer_memory_size());
120+
}
121+
122+
#[test]
123+
pub fn can_claim_array_with_finite_limit() {
124+
let pool_capacity = 1024;
125+
let pool = Arc::new(GreedyMemoryPool::new(pool_capacity));
126+
127+
let consumer = MemoryConsumer::new("arrow");
128+
let arrow_pool = ArrowMemoryPool::new(pool, consumer);
129+
130+
assert_eq!(arrow_pool.capacity(), pool_capacity);
131+
assert_eq!(arrow_pool.available(), pool_capacity as isize);
132+
133+
let array = Int32Array::from(vec![1, 2, 3, 4, 5]);
134+
claim_array(&array, &arrow_pool);
135+
136+
assert_eq!(arrow_pool.used(), array.get_buffer_memory_size());
137+
assert_eq!(
138+
arrow_pool.available(),
139+
(pool_capacity - array.get_buffer_memory_size()) as isize
140+
);
141+
}
142+
}

datafusion/execution/src/memory_pool/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ use std::hash::{Hash, Hasher};
2323
use std::{cmp::Ordering, sync::Arc, sync::atomic};
2424

2525
mod pool;
26+
27+
#[cfg(feature = "arrow_buffer_pool")]
28+
pub mod arrow;
29+
2630
pub mod proxy {
2731
pub use datafusion_common::utils::proxy::{HashTableAllocExt, VecAllocExt};
2832
}

0 commit comments

Comments
 (0)