You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "notfilippo (via GitHub)" <gi...@apache.org> on 2025/11/25 08:13:19 UTC

[PR] feat(memory-tracking): implement arrow_buffer::MemoryPool for MemoryPool [datafusion]

notfilippo opened a new pull request, #18928:
URL: https://github.com/apache/datafusion/pull/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 #123` indicates that this PR will close issue #123.
   -->
   
   - Closes #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 #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.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(memory-tracking): implement arrow_buffer::MemoryPool for MemoryPool [datafusion]

Posted by "notfilippo (via GitHub)" <gi...@apache.org>.
notfilippo commented on code in PR #18928:
URL: https://github.com/apache/datafusion/pull/18928#discussion_r2804718029


##########
datafusion/execution/src/memory_pool/arrow.rs:
##########
@@ -0,0 +1,121 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Adapter for integrating DataFusion's [`MemoryPool`] with Arrow's memory tracking APIs.
+
+use crate::memory_pool::{MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation};
+use std::fmt::Debug;
+use std::sync::Arc;
+
+/// An adapter that implements Arrow's [`arrow_buffer::MemoryPool`] trait
+/// by wrapping a DataFusion [`MemoryPool`].
+///
+/// This allows DataFusion's memory management system to be used with Arrow's
+/// memory allocation APIs. Each reservation made through this pool will be
+/// tracked using the provided [`MemoryConsumer`], enabling DataFusion to
+/// monitor and limit memory usage across Arrow operations.
+///
+/// This is useful when you want Arrow operations (such as array builders
+/// or compute kernels) to participate in DataFusion's memory management
+/// and respect the same memory limits as DataFusion operators.
+#[derive(Debug)]
+pub struct ArrowMemoryPool {
+    inner: Arc<dyn MemoryPool>,
+    consumer: MemoryConsumer,
+}
+
+impl ArrowMemoryPool {
+    /// Creates a new [`ArrowMemoryPool`] that wraps the given DataFusion [`MemoryPool`]
+    /// and tracks allocations under the specified [`MemoryConsumer`].
+    pub fn new(inner: Arc<dyn MemoryPool>, consumer: MemoryConsumer) -> Self {
+        Self { inner, consumer }
+    }
+}
+
+impl arrow_buffer::MemoryReservation for MemoryReservation {
+    fn size(&self) -> usize {
+        MemoryReservation::size(self)
+    }
+
+    fn resize(&mut self, new_size: usize) {
+        MemoryReservation::resize(self, new_size)
+    }
+}
+
+impl arrow_buffer::MemoryPool for ArrowMemoryPool {
+    fn reserve(&self, size: usize) -> Box<dyn arrow_buffer::MemoryReservation> {
+        let consumer = self.consumer.clone_with_new_id();
+        let mut reservation = consumer.register(&self.inner);
+        reservation.grow(size);
+
+        Box::new(reservation)
+    }
+
+    fn available(&self) -> isize {
+        // The pool may be overfilled, so this method might return a negative value.
+        (self.capacity() as i128 - self.used() as i128)
+            .try_into()
+            .unwrap_or(isize::MIN)
+    }
+
+    fn used(&self) -> usize {
+        self.inner.reserved()
+    }
+
+    fn capacity(&self) -> usize {
+        match self.inner.memory_limit() {
+            MemoryLimit::Infinite | MemoryLimit::Unknown => usize::MAX,
+            MemoryLimit::Finite(capacity) => capacity,
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::memory_pool::UnboundedMemoryPool;
+    use arrow::array::{Array, Int32Array};
+    use arrow_buffer::MemoryPool;
+
+    #[test]
+    pub fn can_claim_array() {
+        let pool = Arc::new(UnboundedMemoryPool::default());

Review Comment:
   Just saw this review! Will implement the test.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(memory-tracking): implement arrow_buffer::MemoryPool for MemoryPool [datafusion]

Posted by "notfilippo (via GitHub)" <gi...@apache.org>.
notfilippo commented on code in PR #18928:
URL: https://github.com/apache/datafusion/pull/18928#discussion_r2558937086


##########
datafusion/execution/Cargo.toml:
##########
@@ -46,10 +46,14 @@ default = ["sql"]
 parquet_encryption = [
     "parquet/encryption",
 ]
+arrow_buffer_pool = [

Review Comment:
   The name is fairly descriptive. Maybe we could change it to something better.  I'm open to suggestions!



##########
datafusion/execution/src/memory_pool/arrow.rs:
##########
@@ -0,0 +1,104 @@
+//! Adapter for integrating DataFusion's [`MemoryPool`] with Arrow's memory tracking APIs.
+
+use crate::memory_pool::{MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation};
+use std::fmt::Debug;
+use std::sync::Arc;
+
+/// An adapter that implements Arrow's [`arrow_buffer::MemoryPool`] trait
+/// by wrapping a DataFusion [`MemoryPool`].
+///
+/// This allows DataFusion's memory management system to be used with Arrow's
+/// memory allocation APIs. Each reservation made through this pool will be
+/// tracked using the provided [`MemoryConsumer`], enabling DataFusion to
+/// monitor and limit memory usage across Arrow operations.
+///
+/// This is useful when you want Arrow operations (such as array builders
+/// or compute kernels) to participate in DataFusion's memory management
+/// and respect the same memory limits as DataFusion operators.
+#[derive(Debug)]
+pub struct ArrowMemoryPool {
+    inner: Arc<dyn MemoryPool>,
+    consumer: MemoryConsumer,
+}
+
+impl ArrowMemoryPool {
+    /// Creates a new [`ArrowMemoryPool`] that wraps the given DataFusion [`MemoryPool`]
+    /// and tracks allocations under the specified [`MemoryConsumer`].
+    pub fn new(inner: Arc<dyn MemoryPool>, consumer: MemoryConsumer) -> Self {
+        Self { inner, consumer }
+    }
+}
+
+impl arrow_buffer::MemoryReservation for MemoryReservation {
+    fn size(&self) -> usize {
+        MemoryReservation::size(self)
+    }
+
+    fn resize(&mut self, new_size: usize) {
+        MemoryReservation::resize(self, new_size)
+    }
+}
+
+impl arrow_buffer::MemoryPool for ArrowMemoryPool {
+    fn reserve(&self, size: usize) -> Box<dyn arrow_buffer::MemoryReservation> {
+        let consumer = self.consumer.clone_with_new_id();
+        let mut reservation = consumer.register(&self.inner);
+        reservation.grow(size);
+
+        Box::new(reservation)
+    }
+
+    fn available(&self) -> isize {
+        // The pool may be overfilled, so this method might return a negative value.
+        (self.capacity() as i128 - self.used() as i128)
+            .try_into()
+            .unwrap_or(isize::MIN)
+    }
+
+    fn used(&self) -> usize {
+        self.inner.reserved()
+    }
+
+    fn capacity(&self) -> usize {
+        match self.inner.memory_limit() {
+            MemoryLimit::Infinite | MemoryLimit::Unknown => usize::MAX,
+            MemoryLimit::Finite(capacity) => capacity,
+        }
+    }

Review Comment:
   I'm not really sure these methods have a use-case... I'm open to removing them in the upstream trait.



##########
datafusion/execution/Cargo.toml:
##########
@@ -46,10 +46,14 @@ default = ["sql"]
 parquet_encryption = [
     "parquet/encryption",
 ]
+arrow_buffer_pool = [

Review Comment:
   The feature-flag name is fairly descriptive. Maybe we could change it to something better.  I'm open to suggestions!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(memory-tracking): implement arrow_buffer::MemoryPool for MemoryPool [datafusion]

Posted by "notfilippo (via GitHub)" <gi...@apache.org>.
notfilippo commented on PR #18928:
URL: https://github.com/apache/datafusion/pull/18928#issuecomment-3897828365

   @kosiew thanks for the review! It's ready to be merged.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(memory-tracking): implement arrow_buffer::MemoryPool for MemoryPool [datafusion]

Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on code in PR #18928:
URL: https://github.com/apache/datafusion/pull/18928#discussion_r2703710526


##########
datafusion/execution/src/memory_pool/arrow.rs:
##########
@@ -0,0 +1,121 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Adapter for integrating DataFusion's [`MemoryPool`] with Arrow's memory tracking APIs.
+
+use crate::memory_pool::{MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation};
+use std::fmt::Debug;
+use std::sync::Arc;
+
+/// An adapter that implements Arrow's [`arrow_buffer::MemoryPool`] trait
+/// by wrapping a DataFusion [`MemoryPool`].
+///
+/// This allows DataFusion's memory management system to be used with Arrow's
+/// memory allocation APIs. Each reservation made through this pool will be
+/// tracked using the provided [`MemoryConsumer`], enabling DataFusion to
+/// monitor and limit memory usage across Arrow operations.
+///
+/// This is useful when you want Arrow operations (such as array builders
+/// or compute kernels) to participate in DataFusion's memory management
+/// and respect the same memory limits as DataFusion operators.
+#[derive(Debug)]
+pub struct ArrowMemoryPool {
+    inner: Arc<dyn MemoryPool>,
+    consumer: MemoryConsumer,
+}
+
+impl ArrowMemoryPool {
+    /// Creates a new [`ArrowMemoryPool`] that wraps the given DataFusion [`MemoryPool`]
+    /// and tracks allocations under the specified [`MemoryConsumer`].
+    pub fn new(inner: Arc<dyn MemoryPool>, consumer: MemoryConsumer) -> Self {
+        Self { inner, consumer }
+    }
+}
+
+impl arrow_buffer::MemoryReservation for MemoryReservation {
+    fn size(&self) -> usize {
+        MemoryReservation::size(self)
+    }
+
+    fn resize(&mut self, new_size: usize) {
+        MemoryReservation::resize(self, new_size)
+    }
+}
+
+impl arrow_buffer::MemoryPool for ArrowMemoryPool {
+    fn reserve(&self, size: usize) -> Box<dyn arrow_buffer::MemoryReservation> {
+        let consumer = self.consumer.clone_with_new_id();
+        let mut reservation = consumer.register(&self.inner);
+        reservation.grow(size);
+
+        Box::new(reservation)
+    }
+
+    fn available(&self) -> isize {
+        // The pool may be overfilled, so this method might return a negative value.
+        (self.capacity() as i128 - self.used() as i128)
+            .try_into()
+            .unwrap_or(isize::MIN)
+    }
+
+    fn used(&self) -> usize {
+        self.inner.reserved()
+    }
+
+    fn capacity(&self) -> usize {
+        match self.inner.memory_limit() {
+            MemoryLimit::Infinite | MemoryLimit::Unknown => usize::MAX,
+            MemoryLimit::Finite(capacity) => capacity,
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::memory_pool::UnboundedMemoryPool;
+    use arrow::array::{Array, Int32Array};
+    use arrow_buffer::MemoryPool;
+
+    #[test]
+    pub fn can_claim_array() {
+        let pool = Arc::new(UnboundedMemoryPool::default());

Review Comment:
   how about adding tests for the MemoryLimit::Finite branch too?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(memory-tracking): implement arrow_buffer::MemoryPool for MemoryPool [datafusion]

Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew merged PR #18928:
URL: https://github.com/apache/datafusion/pull/18928


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org