You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "sunchao (via GitHub)" <gi...@apache.org> on 2024/02/22 01:13:41 UTC

[PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

sunchao opened a new pull request, #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83

   ## 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 #.
   
   ## 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.  
   -->
   
   ## 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.
   -->
   
   This PR introduces a `CometMemoryPool` class on the native side, overriding the default memory pool used by DF. This memory pool dispatches calls to Spark's `TaskMemoryManager` for acquiring and releasing memory. 
   
   The newly added memory pool will only be activated when `spark.memory.offHeap.enabled` is set to `true`. Otherwise, the behavior remains the same as before (and `spark.executor.memoryOverhead` need to be large enough for native execution). In `TestBosonBase`, `spark.memory.offHeap.enabled` is enabled so all the tests within Comet are tested with the new feature.
   
   ## How 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)?
   -->
   


-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1511494816


##########
core/src/execution/memory_pool.rs:
##########
@@ -0,0 +1,102 @@
+// 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.
+
+use std::{
+    fmt::{Debug, Formatter, Result as FmtResult},
+    sync::{
+        atomic::{AtomicUsize, Ordering::Relaxed},
+        Arc,
+    },
+};
+
+use jni::objects::GlobalRef;
+
+use datafusion::{
+    common::DataFusionError,
+    execution::memory_pool::{MemoryPool, MemoryReservation},
+};
+
+use crate::jvm_bridge::{jni_call, JVMClasses};
+
+pub struct CometMemoryPool {
+    task_memory_manager_handle: Arc<GlobalRef>,
+    used: AtomicUsize,
+}
+
+impl Debug for CometMemoryPool {
+    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
+        f.debug_struct("CometMemoryPool")
+            .field("used", &self.used.load(Relaxed))
+            .finish()
+    }
+}
+
+impl CometMemoryPool {
+    pub fn new(task_memory_manager_handle: Arc<GlobalRef>) -> CometMemoryPool {
+        Self {
+            task_memory_manager_handle,
+            used: AtomicUsize::new(0),
+        }
+    }
+}
+
+unsafe impl Send for CometMemoryPool {}
+unsafe impl Sync for CometMemoryPool {}
+
+impl MemoryPool for CometMemoryPool {
+    fn grow(&self, _: &MemoryReservation, additional: usize) {
+        self.used.fetch_add(additional, Relaxed);
+    }

Review Comment:
   I think `grow` is not really used by DataFusion except in tests, that's why I didn't do it. But you are right, it's better to add it too for future proof.



##########
core/src/execution/memory_pool.rs:
##########
@@ -0,0 +1,102 @@
+// 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.
+
+use std::{
+    fmt::{Debug, Formatter, Result as FmtResult},
+    sync::{
+        atomic::{AtomicUsize, Ordering::Relaxed},
+        Arc,
+    },
+};
+
+use jni::objects::GlobalRef;
+
+use datafusion::{
+    common::DataFusionError,
+    execution::memory_pool::{MemoryPool, MemoryReservation},
+};
+
+use crate::jvm_bridge::{jni_call, JVMClasses};
+
+pub struct CometMemoryPool {
+    task_memory_manager_handle: Arc<GlobalRef>,
+    used: AtomicUsize,
+}
+
+impl Debug for CometMemoryPool {
+    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
+        f.debug_struct("CometMemoryPool")
+            .field("used", &self.used.load(Relaxed))
+            .finish()
+    }
+}
+
+impl CometMemoryPool {
+    pub fn new(task_memory_manager_handle: Arc<GlobalRef>) -> CometMemoryPool {
+        Self {
+            task_memory_manager_handle,
+            used: AtomicUsize::new(0),
+        }
+    }
+}
+
+unsafe impl Send for CometMemoryPool {}
+unsafe impl Sync for CometMemoryPool {}
+
+impl MemoryPool for CometMemoryPool {
+    fn grow(&self, _: &MemoryReservation, additional: usize) {
+        self.used.fetch_add(additional, Relaxed);
+    }
+
+    fn shrink(&self, _: &MemoryReservation, size: usize) {
+        let mut env = JVMClasses::get_env();
+        let handle = self.task_memory_manager_handle.as_obj();
+        unsafe {
+            jni_call!(&mut env, comet_task_memory_manager(handle).release_memory(size as i64) -> ())
+                .unwrap();
+        }
+        self.used.fetch_sub(size, Relaxed);
+    }
+
+    fn try_grow(&self, _: &MemoryReservation, additional: usize) -> Result<(), DataFusionError> {
+        if additional > 0 {
+            let mut env = JVMClasses::get_env();
+            let handle = self.task_memory_manager_handle.as_obj();
+            unsafe {
+                let acquired = jni_call!(&mut env,
+                  comet_task_memory_manager(handle).acquire_memory(additional as i64) -> i64)?;
+
+                // If the number of bytes we acquired is less than the requested, return an error,
+                // and hopefully will trigger spilling from the caller side.
+                if acquired < additional as i64 {
+                    return Err(DataFusionError::Execution(format!(
+                        "Failed to acquire {} bytes, only got {}. Reserved: {}",
+                        additional,
+                        acquired,
+                        self.reserved(),
+                    )));
+                }

Review Comment:
   Good point. Will add.



##########
core/src/jvm_bridge/comet_task_memory_manager.rs:
##########
@@ -0,0 +1,62 @@
+// 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.
+
+use jni::{
+    errors::Result as JniResult,
+    objects::{JClass, JMethodID},
+    signature::{Primitive, ReturnType},
+    JNIEnv,
+};
+
+use crate::jvm_bridge::get_global_jclass;
+
+/// A DataFusion `MemoryPool` implementation for Comet, which delegate to the JVM
+/// side `CometTaskMemoryManager`.

Review Comment:
   Yea let me move it. 



##########
spark/src/test/scala/org/apache/spark/sql/CometTPCHQuerySuite.scala:
##########
@@ -87,10 +89,11 @@ class CometTPCHQuerySuite extends QueryTest with CometTPCBase with SQLQueryTestH
       "org.apache.spark.sql.comet.execution.shuffle.CometShuffleManager")
     conf.set(CometConf.COMET_ENABLED.key, "true")
     conf.set(CometConf.COMET_EXEC_ENABLED.key, "true")
-    conf.set(CometConf.COMET_MEMORY_OVERHEAD.key, "2g")

Review Comment:
   This is now replaced by 
   
   ```
   conf.set(MEMORY_OFFHEAP_ENABLED.key, "true")
   conf.set(MEMORY_OFFHEAP_SIZE.key, "2g")
   ```
   
   below



##########
spark/src/test/scala/org/apache/spark/sql/CometTestBase.scala:
##########
@@ -65,28 +64,18 @@ abstract class CometTestBase
     val conf = new SparkConf()
     conf.set("spark.hadoop.fs.file.impl", classOf[DebugFilesystem].getName)
     conf.set(SQLConf.SHUFFLE_PARTITIONS, 10) // reduce parallelism in tests
-    conf.set("spark.shuffle.manager", shuffleManager)
+    conf.set(SQLConf.ANSI_ENABLED.key, "false")
+    conf.set(SHUFFLE_MANAGER, shuffleManager)
+    conf.set(MEMORY_OFFHEAP_ENABLED.key, "true")
+    conf.set(MEMORY_OFFHEAP_SIZE.key, "2g")
+    conf.set(CometConf.COMET_ENABLED.key, "true")
+    conf.set(CometConf.COMET_EXEC_ENABLED.key, "true")
+    conf.set(CometConf.COMET_EXEC_ALL_OPERATOR_ENABLED.key, "true")
+    conf.set(CometConf.COMET_EXEC_ALL_EXPR_ENABLED.key, "true")
     conf.set(CometConf.COMET_MEMORY_OVERHEAD.key, "2g")
     conf
   }
 
-  override protected def test(testName: String, testTags: Tag*)(testFun: => Any)(implicit
-      pos: Position): Unit = {
-    super.test(testName, testTags: _*) {
-      withSQLConf(
-        CometConf.COMET_ENABLED.key -> "true",
-        CometConf.COMET_EXEC_ENABLED.key -> "true",
-        CometConf.COMET_EXEC_ALL_OPERATOR_ENABLED.key -> "true",
-        CometConf.COMET_EXEC_ALL_EXPR_ENABLED.key -> "true",
-        CometConf.COMET_COLUMNAR_SHUFFLE_MEMORY_SIZE.key -> "2g",
-        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "1g",
-        SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "1g",

Review Comment:
   Oops I accidentally removed these when rebasing. Let me add them back.



##########
spark/src/main/java/org/apache/spark/CometTaskMemoryManager.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark;
+
+import java.io.IOException;
+
+import org.apache.spark.memory.MemoryConsumer;
+import org.apache.spark.memory.MemoryMode;
+import org.apache.spark.memory.TaskMemoryManager;
+
+/**
+ * A adapter class that is used by Comet native to acquire & release memory through Spark's unified
+ * memory manager. This assumes Spark's off-heap memory mode is enabled.
+ */
+public class CometTaskMemoryManager {
+  /** The id uniquely identifies the native plan this memory manager is associated to */
+  private final long id;
+
+  private final TaskMemoryManager internal;
+  private final NativeMemoryConsumer nativeMemoryConsumer;
+
+  public CometTaskMemoryManager(long id) {
+    this.id = id;
+    this.internal = TaskContext$.MODULE$.get().taskMemoryManager();
+    this.nativeMemoryConsumer = new NativeMemoryConsumer();
+  }
+
+  // Called by Comet native through JNI.
+  // Returns the actual amount of memory (in bytes) granted.
+  public long acquireMemory(long size) {
+    return internal.acquireExecutionMemory(size, nativeMemoryConsumer);
+  }

Review Comment:
   I think `TaskMemoryManager` is already synchronized on the `acquireExecutionMemory` and `releaseExecutionMemory`, so it doesn't seem necessary.



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "advancedxy (via GitHub)" <gi...@apache.org>.
advancedxy commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1506956772


##########
spark/src/test/scala/org/apache/spark/sql/CometTestBase.scala:
##########
@@ -65,28 +64,18 @@ abstract class CometTestBase
     val conf = new SparkConf()
     conf.set("spark.hadoop.fs.file.impl", classOf[DebugFilesystem].getName)
     conf.set(SQLConf.SHUFFLE_PARTITIONS, 10) // reduce parallelism in tests
-    conf.set("spark.shuffle.manager", shuffleManager)
+    conf.set(SQLConf.ANSI_ENABLED.key, "false")
+    conf.set(SHUFFLE_MANAGER, shuffleManager)
+    conf.set(MEMORY_OFFHEAP_ENABLED.key, "true")

Review Comment:
   > Ideally we should be able to use DriverPlugin to override the memory settings so Comet may just work out of box (need to change Spark in a few places).
   
   Oh. It seems that DriverPlugin is initialized before task scheduler. Which places in Spark do we need for CometDriverPlugin to override memory settings? The memory overhead is already override by comet.
   
   >and can probably do the same here too.
   
   Is this still in this PR's scope?



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "advancedxy (via GitHub)" <gi...@apache.org>.
advancedxy commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1507055191


##########
spark/src/test/scala/org/apache/spark/sql/CometTestBase.scala:
##########
@@ -65,28 +64,18 @@ abstract class CometTestBase
     val conf = new SparkConf()
     conf.set("spark.hadoop.fs.file.impl", classOf[DebugFilesystem].getName)
     conf.set(SQLConf.SHUFFLE_PARTITIONS, 10) // reduce parallelism in tests
-    conf.set("spark.shuffle.manager", shuffleManager)
+    conf.set(SQLConf.ANSI_ENABLED.key, "false")
+    conf.set(SHUFFLE_MANAGER, shuffleManager)
+    conf.set(MEMORY_OFFHEAP_ENABLED.key, "true")

Review Comment:
   > I already made one change in Spark: https://github.com/apache/spark/pull/45052 for this. We'll need a few more changes so we can completely overwrite executor memory setting through DriverPlugin.
   
   Great work. Looking forward that we can completely overwrite memory settings through DriverPlugin.



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "snmvaughan (via GitHub)" <gi...@apache.org>.
snmvaughan commented on PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#issuecomment-1975198074

   LGTM.  Good catch on `check_exception` in `jni_call`.


-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#issuecomment-1962078518

   Thanks @sunchao. I will review this in next days (or week).


-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1510666577


##########
spark/src/test/scala/org/apache/spark/sql/CometTPCHQuerySuite.scala:
##########
@@ -87,10 +89,11 @@ class CometTPCHQuerySuite extends QueryTest with CometTPCBase with SQLQueryTestH
       "org.apache.spark.sql.comet.execution.shuffle.CometShuffleManager")
     conf.set(CometConf.COMET_ENABLED.key, "true")
     conf.set(CometConf.COMET_EXEC_ENABLED.key, "true")
-    conf.set(CometConf.COMET_MEMORY_OVERHEAD.key, "2g")

Review Comment:
   We don't need it?



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#issuecomment-1962074048

   cc @viirya 


-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1510661145


##########
core/src/execution/memory_pool.rs:
##########
@@ -0,0 +1,102 @@
+// 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.
+
+use std::{
+    fmt::{Debug, Formatter, Result as FmtResult},
+    sync::{
+        atomic::{AtomicUsize, Ordering::Relaxed},
+        Arc,
+    },
+};
+
+use jni::objects::GlobalRef;
+
+use datafusion::{
+    common::DataFusionError,
+    execution::memory_pool::{MemoryPool, MemoryReservation},
+};
+
+use crate::jvm_bridge::{jni_call, JVMClasses};
+
+pub struct CometMemoryPool {
+    task_memory_manager_handle: Arc<GlobalRef>,
+    used: AtomicUsize,
+}
+
+impl Debug for CometMemoryPool {
+    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
+        f.debug_struct("CometMemoryPool")
+            .field("used", &self.used.load(Relaxed))
+            .finish()
+    }
+}
+
+impl CometMemoryPool {
+    pub fn new(task_memory_manager_handle: Arc<GlobalRef>) -> CometMemoryPool {
+        Self {
+            task_memory_manager_handle,
+            used: AtomicUsize::new(0),
+        }
+    }
+}
+
+unsafe impl Send for CometMemoryPool {}
+unsafe impl Sync for CometMemoryPool {}
+
+impl MemoryPool for CometMemoryPool {
+    fn grow(&self, _: &MemoryReservation, additional: usize) {
+        self.used.fetch_add(additional, Relaxed);
+    }
+
+    fn shrink(&self, _: &MemoryReservation, size: usize) {
+        let mut env = JVMClasses::get_env();
+        let handle = self.task_memory_manager_handle.as_obj();
+        unsafe {
+            jni_call!(&mut env, comet_task_memory_manager(handle).release_memory(size as i64) -> ())
+                .unwrap();
+        }
+        self.used.fetch_sub(size, Relaxed);
+    }
+
+    fn try_grow(&self, _: &MemoryReservation, additional: usize) -> Result<(), DataFusionError> {
+        if additional > 0 {
+            let mut env = JVMClasses::get_env();
+            let handle = self.task_memory_manager_handle.as_obj();
+            unsafe {
+                let acquired = jni_call!(&mut env,
+                  comet_task_memory_manager(handle).acquire_memory(additional as i64) -> i64)?;
+
+                // If the number of bytes we acquired is less than the requested, return an error,
+                // and hopefully will trigger spilling from the caller side.
+                if acquired < additional as i64 {
+                    return Err(DataFusionError::Execution(format!(
+                        "Failed to acquire {} bytes, only got {}. Reserved: {}",
+                        additional,
+                        acquired,
+                        self.reserved(),
+                    )));
+                }

Review Comment:
   When we fail to get the required number and return error, I think we should notify the JVM memory manager to release the allocated `acquired` bytes.



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1510664052


##########
spark/src/main/java/org/apache/spark/CometTaskMemoryManager.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark;
+
+import java.io.IOException;
+
+import org.apache.spark.memory.MemoryConsumer;
+import org.apache.spark.memory.MemoryMode;
+import org.apache.spark.memory.TaskMemoryManager;
+
+/**
+ * A adapter class that is used by Comet native to acquire & release memory through Spark's unified
+ * memory manager. This assumes Spark's off-heap memory mode is enabled.
+ */
+public class CometTaskMemoryManager {
+  /** The id uniquely identifies the native plan this memory manager is associated to */
+  private final long id;
+
+  private final TaskMemoryManager internal;
+  private final NativeMemoryConsumer nativeMemoryConsumer;
+
+  public CometTaskMemoryManager(long id) {
+    this.id = id;
+    this.internal = TaskContext$.MODULE$.get().taskMemoryManager();
+    this.nativeMemoryConsumer = new NativeMemoryConsumer();
+  }
+
+  // Called by Comet native through JNI.
+  // Returns the actual amount of memory (in bytes) granted.
+  public long acquireMemory(long size) {
+    return internal.acquireExecutionMemory(size, nativeMemoryConsumer);
+  }

Review Comment:
   As we claim `Send` and `Sync` for `CometMemoryPool`, should we make this synchronized method? 



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1511526010


##########
spark/src/main/java/org/apache/spark/CometTaskMemoryManager.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark;
+
+import java.io.IOException;
+
+import org.apache.spark.memory.MemoryConsumer;
+import org.apache.spark.memory.MemoryMode;
+import org.apache.spark.memory.TaskMemoryManager;
+
+/**
+ * A adapter class that is used by Comet native to acquire & release memory through Spark's unified
+ * memory manager. This assumes Spark's off-heap memory mode is enabled.
+ */
+public class CometTaskMemoryManager {
+  /** The id uniquely identifies the native plan this memory manager is associated to */
+  private final long id;
+
+  private final TaskMemoryManager internal;
+  private final NativeMemoryConsumer nativeMemoryConsumer;
+
+  public CometTaskMemoryManager(long id) {
+    this.id = id;
+    this.internal = TaskContext$.MODULE$.get().taskMemoryManager();
+    this.nativeMemoryConsumer = new NativeMemoryConsumer();
+  }
+
+  // Called by Comet native through JNI.
+  // Returns the actual amount of memory (in bytes) granted.
+  public long acquireMemory(long size) {
+    return internal.acquireExecutionMemory(size, nativeMemoryConsumer);
+  }

Review Comment:
   Oh okay, then it is fine.



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#issuecomment-1979612979

   @sunchao Do you see we use less memory than before this patch when running TPCH/TPCDS queries on EKS?


-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1503800708


##########
spark/src/main/java/org/apache/spark/CometTaskMemoryManager.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark;
+
+import java.io.IOException;
+
+import org.apache.spark.memory.MemoryConsumer;
+import org.apache.spark.memory.MemoryMode;
+import org.apache.spark.memory.TaskMemoryManager;
+
+/**
+ * A adapter class that is used by Comet native to acquire & release memory through Spark's unified
+ * memory manager. This assumes Spark's off-heap memory mode is enabled.
+ */
+public class CometTaskMemoryManager {
+  private final TaskMemoryManager internal;
+  private final NativeMemoryConsumer nativeMemoryConsumer;
+
+  public CometTaskMemoryManager() {
+    this.internal = TaskContext$.MODULE$.get().taskMemoryManager();
+    this.nativeMemoryConsumer = new NativeMemoryConsumer();
+  }
+
+  // Called by Comet native through JNI.
+  // Returns the actual amount of memory (in bytes) granted.
+  public long acquireMemory(long size) {
+    return internal.acquireExecutionMemory(size, nativeMemoryConsumer);
+  }
+
+  // Called by Comet native through JNI
+  public void releaseMemory(long size) {
+    internal.releaseExecutionMemory(size, nativeMemoryConsumer);
+  }
+
+  /**
+   * A dummy memory consumer that does nothing when spilling. At the moment, Comet native doesn't
+   * share the same API as Spark and cannot trigger spill when acquire memory. Therefore, when
+   * acquiring memory from native or JVM, spilling can only be triggered from JVM operators.
+   */
+  private class NativeMemoryConsumer extends MemoryConsumer {

Review Comment:
   Sure, I can add a `toString` for now and we can figure out how to use it for debugging purpose later.



##########
core/src/execution/jni_api.rs:
##########
@@ -103,6 +103,7 @@ pub unsafe extern "system" fn Java_org_apache_comet_Native_createPlan(
     iterators: jobjectArray,
     serialized_query: jbyteArray,
     metrics_node: JObject,
+    task_memory_manager_obj: JObject,

Review Comment:
   Sure



##########
spark/src/test/scala/org/apache/spark/sql/CometTestBase.scala:
##########
@@ -65,28 +64,18 @@ abstract class CometTestBase
     val conf = new SparkConf()
     conf.set("spark.hadoop.fs.file.impl", classOf[DebugFilesystem].getName)
     conf.set(SQLConf.SHUFFLE_PARTITIONS, 10) // reduce parallelism in tests
-    conf.set("spark.shuffle.manager", shuffleManager)
+    conf.set(SQLConf.ANSI_ENABLED.key, "false")
+    conf.set(SHUFFLE_MANAGER, shuffleManager)
+    conf.set(MEMORY_OFFHEAP_ENABLED.key, "true")

Review Comment:
   In the long term I'm thinking to only use the memory pool defined in Comet. This currently requires users to turn on off-heap mode in Spark and set the off-heap memory accordingly, so configuration changes are necessary when they want to use Comet. Ideally we should be able to use `DriverPlugin` to override the memory settings so Comet may just work out of box (need to change Spark in a few places).
   
   The default memory manager path is kept only for now until we are able to do the override through `DriverPlugin`. Internally we still run all the Spark SQL tests using the default memory manager, and can probably do the same here too. 



##########
core/src/execution/jni_api.rs:
##########
@@ -186,18 +189,29 @@ fn prepare_datafusion_session_context(
 
     let mut rt_config = RuntimeConfig::new().with_disk_manager(DiskManagerConfig::NewOs);
 
-    // Set up memory limit if specified
-    if conf.contains_key("memory_limit") {
-        let memory_limit = conf.get("memory_limit").unwrap().parse::<usize>()?;
-
-        let memory_fraction = conf
-            .get("memory_fraction")
-            .ok_or(CometError::Internal(
-                "Config 'memory_fraction' is not specified from Comet JVM side".to_string(),
-            ))?
-            .parse::<f64>()?;
-
-        rt_config = rt_config.with_memory_limit(memory_limit, memory_fraction);
+    let use_unified_memory_manager = conf
+        .get("use_unified_memory_manager")
+        .ok_or(CometError::Internal(
+            "Config 'use_unified_memory_manager' is not specified from Comet JVM side".to_string(),
+        ))?

Review Comment:
   Yea sure, although this is an internal error from developer side if not set.



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1510657778


##########
core/src/execution/memory_pool.rs:
##########
@@ -0,0 +1,102 @@
+// 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.
+
+use std::{
+    fmt::{Debug, Formatter, Result as FmtResult},
+    sync::{
+        atomic::{AtomicUsize, Ordering::Relaxed},
+        Arc,
+    },
+};
+
+use jni::objects::GlobalRef;
+
+use datafusion::{
+    common::DataFusionError,
+    execution::memory_pool::{MemoryPool, MemoryReservation},
+};
+
+use crate::jvm_bridge::{jni_call, JVMClasses};
+
+pub struct CometMemoryPool {
+    task_memory_manager_handle: Arc<GlobalRef>,
+    used: AtomicUsize,
+}
+
+impl Debug for CometMemoryPool {
+    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
+        f.debug_struct("CometMemoryPool")
+            .field("used", &self.used.load(Relaxed))
+            .finish()
+    }
+}
+
+impl CometMemoryPool {
+    pub fn new(task_memory_manager_handle: Arc<GlobalRef>) -> CometMemoryPool {
+        Self {
+            task_memory_manager_handle,
+            used: AtomicUsize::new(0),
+        }
+    }
+}
+
+unsafe impl Send for CometMemoryPool {}
+unsafe impl Sync for CometMemoryPool {}
+
+impl MemoryPool for CometMemoryPool {
+    fn grow(&self, _: &MemoryReservation, additional: usize) {
+        self.used.fetch_add(additional, Relaxed);
+    }

Review Comment:
   Don't we need to update (acquire) the required memory from JVM memory manager?



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1510667483


##########
spark/src/test/scala/org/apache/spark/sql/CometTestBase.scala:
##########
@@ -65,28 +64,18 @@ abstract class CometTestBase
     val conf = new SparkConf()
     conf.set("spark.hadoop.fs.file.impl", classOf[DebugFilesystem].getName)
     conf.set(SQLConf.SHUFFLE_PARTITIONS, 10) // reduce parallelism in tests
-    conf.set("spark.shuffle.manager", shuffleManager)
+    conf.set(SQLConf.ANSI_ENABLED.key, "false")
+    conf.set(SHUFFLE_MANAGER, shuffleManager)
+    conf.set(MEMORY_OFFHEAP_ENABLED.key, "true")
+    conf.set(MEMORY_OFFHEAP_SIZE.key, "2g")
+    conf.set(CometConf.COMET_ENABLED.key, "true")
+    conf.set(CometConf.COMET_EXEC_ENABLED.key, "true")
+    conf.set(CometConf.COMET_EXEC_ALL_OPERATOR_ENABLED.key, "true")
+    conf.set(CometConf.COMET_EXEC_ALL_EXPR_ENABLED.key, "true")
     conf.set(CometConf.COMET_MEMORY_OVERHEAD.key, "2g")
     conf
   }
 
-  override protected def test(testName: String, testTags: Tag*)(testFun: => Any)(implicit
-      pos: Position): Unit = {
-    super.test(testName, testTags: _*) {
-      withSQLConf(
-        CometConf.COMET_ENABLED.key -> "true",
-        CometConf.COMET_EXEC_ENABLED.key -> "true",
-        CometConf.COMET_EXEC_ALL_OPERATOR_ENABLED.key -> "true",
-        CometConf.COMET_EXEC_ALL_EXPR_ENABLED.key -> "true",
-        CometConf.COMET_COLUMNAR_SHUFFLE_MEMORY_SIZE.key -> "2g",
-        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "1g",
-        SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "1g",

Review Comment:
   For broadcast join threshold configs, should we keep them?



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#issuecomment-1980133662

   Thanks, 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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1506959941


##########
spark/src/test/scala/org/apache/spark/sql/CometTestBase.scala:
##########
@@ -65,28 +64,18 @@ abstract class CometTestBase
     val conf = new SparkConf()
     conf.set("spark.hadoop.fs.file.impl", classOf[DebugFilesystem].getName)
     conf.set(SQLConf.SHUFFLE_PARTITIONS, 10) // reduce parallelism in tests
-    conf.set("spark.shuffle.manager", shuffleManager)
+    conf.set(SQLConf.ANSI_ENABLED.key, "false")
+    conf.set(SHUFFLE_MANAGER, shuffleManager)
+    conf.set(MEMORY_OFFHEAP_ENABLED.key, "true")

Review Comment:
   > Oh. It seems that DriverPlugin is initialized before task scheduler. Which places in Spark do we need for CometDriverPlugin to override memory settings? The memory overhead is already override by comet.
   
   I already made one change in Spark: https://github.com/apache/spark/pull/45052 for this. We'll need a few more changes so we can completely overwrite executor memory setting through `DriverPlugin`.
   
   > Is this still in this PR's scope?
   
   Not really. Will do that in https://github.com/apache/arrow-datafusion-comet/issues/8



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1510662268


##########
core/src/jvm_bridge/comet_task_memory_manager.rs:
##########
@@ -0,0 +1,62 @@
+// 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.
+
+use jni::{
+    errors::Result as JniResult,
+    objects::{JClass, JMethodID},
+    signature::{Primitive, ReturnType},
+    JNIEnv,
+};
+
+use crate::jvm_bridge::get_global_jclass;
+
+/// A DataFusion `MemoryPool` implementation for Comet, which delegate to the JVM
+/// side `CometTaskMemoryManager`.

Review Comment:
   The comment looks not correct as `CometMemoryPool` is the one implementing DataFusion `MemoryPool`. Maybe this should be moved to `CometMemoryPool`?



-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao merged PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83


-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#issuecomment-1980133526

   I tried this with columnar shuffle sometime back and in TPC-DS there were other issues that caused OOM. I plan to try benchmarking this again soon. Let me merge this PR first and address remaining issues in follow-ups.


-- 
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@arrow.apache.org

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


Re: [PR] feat: Introduce `CometTaskMemoryManager` and native side memory pool [arrow-datafusion-comet]

Posted by "advancedxy (via GitHub)" <gi...@apache.org>.
advancedxy commented on code in PR #83:
URL: https://github.com/apache/arrow-datafusion-comet/pull/83#discussion_r1502504983


##########
core/src/execution/jni_api.rs:
##########
@@ -103,6 +103,7 @@ pub unsafe extern "system" fn Java_org_apache_comet_Native_createPlan(
     iterators: jobjectArray,
     serialized_query: jbyteArray,
     metrics_node: JObject,
+    task_memory_manager_obj: JObject,

Review Comment:
   how about rename this to `comet_task_memory_manager_obj`? 
   
   When I first read the code, I thought it was the Spark's TaskMemoryManager object. However it's comet's `CometTaskMemoryManager`.   It would be clear to call it `comet_task_memory_manager_obj`
   
   Other occurrence could be renamed too.



##########
spark/src/main/java/org/apache/spark/CometTaskMemoryManager.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark;
+
+import java.io.IOException;
+
+import org.apache.spark.memory.MemoryConsumer;
+import org.apache.spark.memory.MemoryMode;
+import org.apache.spark.memory.TaskMemoryManager;
+
+/**
+ * A adapter class that is used by Comet native to acquire & release memory through Spark's unified
+ * memory manager. This assumes Spark's off-heap memory mode is enabled.
+ */
+public class CometTaskMemoryManager {
+  private final TaskMemoryManager internal;
+  private final NativeMemoryConsumer nativeMemoryConsumer;
+
+  public CometTaskMemoryManager() {
+    this.internal = TaskContext$.MODULE$.get().taskMemoryManager();
+    this.nativeMemoryConsumer = new NativeMemoryConsumer();
+  }
+
+  // Called by Comet native through JNI.
+  // Returns the actual amount of memory (in bytes) granted.
+  public long acquireMemory(long size) {
+    return internal.acquireExecutionMemory(size, nativeMemoryConsumer);
+  }
+
+  // Called by Comet native through JNI
+  public void releaseMemory(long size) {
+    internal.releaseExecutionMemory(size, nativeMemoryConsumer);
+  }
+
+  /**
+   * A dummy memory consumer that does nothing when spilling. At the moment, Comet native doesn't
+   * share the same API as Spark and cannot trigger spill when acquire memory. Therefore, when
+   * acquiring memory from native or JVM, spilling can only be triggered from JVM operators.
+   */
+  private class NativeMemoryConsumer extends MemoryConsumer {

Review Comment:
   The consumer's toString might be used when the debugging log is turned on. 
   
   It would be great that we can override this class to provide `toString` method and also add a unique flag/id to identify the corresponding consumer for the native plan/execution.



##########
core/src/execution/jni_api.rs:
##########
@@ -186,18 +189,29 @@ fn prepare_datafusion_session_context(
 
     let mut rt_config = RuntimeConfig::new().with_disk_manager(DiskManagerConfig::NewOs);
 
-    // Set up memory limit if specified
-    if conf.contains_key("memory_limit") {
-        let memory_limit = conf.get("memory_limit").unwrap().parse::<usize>()?;
-
-        let memory_fraction = conf
-            .get("memory_fraction")
-            .ok_or(CometError::Internal(
-                "Config 'memory_fraction' is not specified from Comet JVM side".to_string(),
-            ))?
-            .parse::<f64>()?;
-
-        rt_config = rt_config.with_memory_limit(memory_limit, memory_fraction);
+    let use_unified_memory_manager = conf
+        .get("use_unified_memory_manager")
+        .ok_or(CometError::Internal(
+            "Config 'use_unified_memory_manager' is not specified from Comet JVM side".to_string(),
+        ))?

Review Comment:
   I believe a more permissive way is to treat **unsetting** `use_unified_memory_manager` as false?



##########
spark/src/test/scala/org/apache/spark/sql/CometTestBase.scala:
##########
@@ -65,28 +64,18 @@ abstract class CometTestBase
     val conf = new SparkConf()
     conf.set("spark.hadoop.fs.file.impl", classOf[DebugFilesystem].getName)
     conf.set(SQLConf.SHUFFLE_PARTITIONS, 10) // reduce parallelism in tests
-    conf.set("spark.shuffle.manager", shuffleManager)
+    conf.set(SQLConf.ANSI_ENABLED.key, "false")
+    conf.set(SHUFFLE_MANAGER, shuffleManager)
+    conf.set(MEMORY_OFFHEAP_ENABLED.key, "true")

Review Comment:
   Are we still going to test the default memory pool implementation in DataFusion?
   
   Seems like all the test code path are the unified memory manager now.



##########
spark/src/main/scala/org/apache/comet/CometExecIterator.scala:
##########
@@ -54,7 +54,13 @@ class CometExecIterator(
   }.toArray
   private val plan = {
     val configs = createNativeConf
-    nativeLib.createPlan(id, configs, cometBatchIterators, protobufQueryPlan, nativeMetrics)
+    nativeLib.createPlan(
+      id,
+      configs,
+      cometBatchIterators,
+      protobufQueryPlan,
+      nativeMetrics,
+      new CometTaskMemoryManager)

Review Comment:
   I'm referring this. I think we can pass `id` to `CometTaskMemoryManager` and use that for identity mark.



-- 
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@arrow.apache.org

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