You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by su...@apache.org on 2026/08/29 17:32:42 UTC

(datafusion-comet) branch main updated: fix: make task-shared memory pool as ref-counted RAII guard (#5494)

This is an automated email from the ASF dual-hosted git repository.

sunchao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git


The following commit(s) were added to refs/heads/main by this push:
     new 215ab706aa fix: make task-shared memory pool as ref-counted RAII guard (#5494)
215ab706aa is described below

commit 215ab706aa9af074e589f400cd6843dee9938030
Author: Peter Lee <pe...@gmail.com>
AuthorDate: Sun Aug 30 01:32:36 2026 +0800

    fix: make task-shared memory pool as ref-counted RAII guard (#5494)
    
    * fix: prevent task-shared memory pool leaks on plan lifecycle failures
    
    Tie TASK_SHARED_MEMORY_POOLS registration to the pool's own Arc lifetime
    (Weak entries + self-removing Drop), reclaim the ExecutionContext before
    the fallible metrics update in releasePlan, and make
    CometExecIterator.close() idempotent while still guaranteeing releasePlan
    when teardown throws.
    
    Part of #5212 (positions 2, 3 and 8). Supersedes #5217.
    
    * ci: register CometExecIteratorLifecycleSuite in PR build workflows
    
    * fix: attempt each resource cleanup independently in CometExecIterator.close
    
    One input's close failure no longer skips the remaining batch, native
    util, or shuffle inputs; failures accumulate as suppressed exceptions
    and the native plan is still released exactly once.
    
    Addresses review feedback on #5494.
    
    * address review feedback: null assert in releasePlan, keep close diagnostics on failure, inline acquire_task_shared_pool, pin metrics-failure test to release path, add registry churn test
---
 .github/workflows/pr_build_linux.yml               |   1 +
 .github/workflows/pr_build_macos.yml               |   1 +
 native/core/src/execution/jni_api.rs               |  40 ++--
 native/core/src/execution/memory_pools/config.rs   |  12 --
 native/core/src/execution/memory_pools/mod.rs      | 112 ++++-------
 .../core/src/execution/memory_pools/task_shared.rs | 216 +++++++++++++++++---
 .../scala/org/apache/comet/CometExecIterator.scala |  54 +++--
 .../spark/CometExecIteratorLifecycleSuite.scala    | 223 +++++++++++++++++++++
 8 files changed, 509 insertions(+), 150 deletions(-)

diff --git a/.github/workflows/pr_build_linux.yml b/.github/workflows/pr_build_linux.yml
index 42653d61e5..9f363ab1c8 100644
--- a/.github/workflows/pr_build_linux.yml
+++ b/.github/workflows/pr_build_linux.yml
@@ -358,6 +358,7 @@ jobs:
               org.apache.comet.CometSparkSessionExtensionsSuite
               org.apache.spark.CometPluginsSuite
               org.apache.spark.CometTaskMemoryManagerSuite
+              org.apache.spark.CometExecIteratorLifecycleSuite
               org.apache.spark.CometPluginsDefaultSuite
               org.apache.spark.CometPluginsNonOverrideSuite
               org.apache.spark.CometPluginsUnifiedModeOverrideSuite
diff --git a/.github/workflows/pr_build_macos.yml b/.github/workflows/pr_build_macos.yml
index f6344cf753..c4146004fc 100644
--- a/.github/workflows/pr_build_macos.yml
+++ b/.github/workflows/pr_build_macos.yml
@@ -174,6 +174,7 @@ jobs:
               org.apache.comet.CometSparkSessionExtensionsSuite
               org.apache.spark.CometPluginsSuite
               org.apache.spark.CometTaskMemoryManagerSuite
+              org.apache.spark.CometExecIteratorLifecycleSuite
               org.apache.spark.CometPluginsDefaultSuite
               org.apache.spark.CometPluginsNonOverrideSuite
               org.apache.spark.CometPluginsUnifiedModeOverrideSuite
diff --git a/native/core/src/execution/jni_api.rs b/native/core/src/execution/jni_api.rs
index 86780d0c90..4d4094b147 100644
--- a/native/core/src/execution/jni_api.rs
+++ b/native/core/src/execution/jni_api.rs
@@ -97,9 +97,7 @@ use std::{sync::Arc, task::Poll};
 use tokio::runtime::{Handle, Runtime};
 use tokio::sync::mpsc;
 
-use crate::execution::memory_pools::{
-    create_memory_pool, handle_task_shared_pool_release, parse_memory_pool_config, MemoryPoolConfig,
-};
+use crate::execution::memory_pools::{create_memory_pool, parse_memory_pool_config};
 use crate::execution::operators::{ScanExec, ShuffleScanExec};
 use crate::execution::shuffle::{
     read_ipc_compressed, read_ipc_compressed_validated, validate_remote_schema, CompressionCodec,
@@ -340,8 +338,6 @@ fn collect_op_names<'a>(op: &'a Operator, names: &mut std::collections::BTreeSet
 struct ExecutionContext {
     /// The id of the execution context.
     pub id: i64,
-    /// Task attempt id
-    pub task_attempt_id: i64,
     /// The deserialized Spark plan
     pub spark_plan: Operator,
     /// The number of partitions
@@ -374,8 +370,6 @@ struct ExecutionContext {
     pub debug_native: bool,
     /// Whether to write native plans with metrics to stdout
     pub explain_native: bool,
-    /// Memory pool config
-    pub memory_pool_config: MemoryPoolConfig,
     /// Whether to log memory usage on each call to execute_plan
     pub tracing_enabled: bool,
     /// Rust thread ID, used for aggregating tracing metrics per thread
@@ -563,7 +557,6 @@ pub unsafe extern "system" fn Java_org_apache_comet_Native_createPlan(
 
             let exec_context = Box::new(ExecutionContext {
                 id,
-                task_attempt_id,
                 spark_plan,
                 partition_count: partition_count as usize,
                 root_op: None,
@@ -580,7 +573,6 @@ pub unsafe extern "system" fn Java_org_apache_comet_Native_createPlan(
                 session_ctx: session,
                 debug_native,
                 explain_native,
-                memory_pool_config,
                 tracing_enabled,
                 rust_thread_id,
                 tracing_memory_metric_name: format!(
@@ -1042,22 +1034,22 @@ pub extern "system" fn Java_org_apache_comet_Native_releasePlan(
     exec_context: jlong,
 ) {
     try_unwrap_or_throw(&e, |env| unsafe {
-        let execution_context = get_execution_context(exec_context);
-
-        // Move the guard out before the fallible metrics update. On error it unregisters while
-        // leaving the raw execution context alive for the JVM's existing release retry.
-        let memory_pool_registration = execution_context.memory_pool_registration.take();
-
-        // Update metrics
-        update_metrics(env, execution_context)?;
-
-        handle_task_shared_pool_release(
-            execution_context.memory_pool_config.pool_type,
-            execution_context.task_attempt_id,
+        // A null pointer from the JVM would be undefined behaviour in `Box::from_raw`; panic
+        // instead, which `try_unwrap_or_throw` converts into a Java exception (this is the check
+        // `get_execution_context` performs for the other JNI entry points).
+        assert_ne!(
+            exec_context, 0,
+            "Comet execution context shouldn't be null!"
         );
 
+        // Reclaim ownership of the context up front so that it is always freed, even if updating
+        // metrics below fails. Dropping it releases the memory pool and every JNI global ref the
+        // context holds.
+        let mut execution_context: Box<ExecutionContext> =
+            Box::from_raw(exec_context as *mut ExecutionContext);
+
         // Unregister this context's pool and emit the remaining total for the thread
-        if let Some(memory_pool_registration) = memory_pool_registration {
+        if let Some(memory_pool_registration) = execution_context.memory_pool_registration.take() {
             let remaining = memory_pool_registration.unregister_and_total();
             log_memory_usage(
                 &execution_context.tracing_memory_metric_name,
@@ -1065,8 +1057,8 @@ pub extern "system" fn Java_org_apache_comet_Native_releasePlan(
             );
         }
 
-        let _: Box<ExecutionContext> = Box::from_raw(execution_context);
-        Ok(())
+        // Flush metrics last, as it is the only fallible step here.
+        update_metrics(env, &mut execution_context)
     })
 }
 
diff --git a/native/core/src/execution/memory_pools/config.rs b/native/core/src/execution/memory_pools/config.rs
index 83d6c14a36..312a360438 100644
--- a/native/core/src/execution/memory_pools/config.rs
+++ b/native/core/src/execution/memory_pools/config.rs
@@ -30,18 +30,6 @@ pub(crate) enum MemoryPoolType {
     Unbounded,
 }
 
-impl MemoryPoolType {
-    pub(crate) fn is_task_shared(&self) -> bool {
-        matches!(
-            self,
-            MemoryPoolType::GreedyTaskShared
-                | MemoryPoolType::FairSpillTaskShared
-                | MemoryPoolType::FairUnified
-                | MemoryPoolType::GreedyUnified
-        )
-    }
-}
-
 pub(crate) struct MemoryPoolConfig {
     pub(crate) pool_type: MemoryPoolType,
     pub(crate) pool_size: usize,
diff --git a/native/core/src/execution/memory_pools/mod.rs b/native/core/src/execution/memory_pools/mod.rs
index 389e348990..d7c2911f91 100644
--- a/native/core/src/execution/memory_pools/mod.rs
+++ b/native/core/src/execution/memory_pools/mod.rs
@@ -34,94 +34,60 @@ use unified_pool::CometUnifiedMemoryPool;
 pub(crate) use config::*;
 pub(crate) use task_shared::*;
 
+/// Creates the memory pool for a native plan.
+///
+/// Task-shared pools use their returned `Arc` as the RAII handle, so they remain registered for as
+/// long as the plan or any of its reservations retain the pool.
 pub(crate) fn create_memory_pool(
     memory_pool_config: &MemoryPoolConfig,
     comet_task_memory_manager: Arc<Global<JObject<'static>>>,
     task_attempt_id: i64,
 ) -> Arc<dyn MemoryPool> {
     const NUM_TRACKED_CONSUMERS: usize = 10;
-    match memory_pool_config.pool_type {
-        MemoryPoolType::GreedyUnified => {
-            let mut memory_pool_map = TASK_SHARED_MEMORY_POOLS.lock().unwrap();
-            let per_task_memory_pool =
-                memory_pool_map.entry(task_attempt_id).or_insert_with(|| {
-                    let pool: Arc<dyn MemoryPool> = Arc::new(TrackConsumersPool::new(
-                        CometUnifiedMemoryPool::new(
-                            Arc::clone(&comet_task_memory_manager),
-                            task_attempt_id,
-                        ),
-                        NonZeroUsize::new(NUM_TRACKED_CONSUMERS).unwrap(),
-                    ));
-                    PerTaskMemoryPool::new(pool)
-                });
-            per_task_memory_pool.num_plans += 1;
-            Arc::clone(&per_task_memory_pool.memory_pool)
-        }
-        MemoryPoolType::FairUnified => {
-            let mut memory_pool_map = TASK_SHARED_MEMORY_POOLS.lock().unwrap();
-            let per_task_memory_pool =
-                memory_pool_map.entry(task_attempt_id).or_insert_with(|| {
-                    let pool: Arc<dyn MemoryPool> = Arc::new(TrackConsumersPool::new(
-                        CometFairMemoryPool::new(
-                            Arc::clone(&comet_task_memory_manager),
-                            memory_pool_config.pool_size,
-                        ),
-                        NonZeroUsize::new(NUM_TRACKED_CONSUMERS).unwrap(),
-                    ));
-                    PerTaskMemoryPool::new(pool)
-                });
-            per_task_memory_pool.num_plans += 1;
-            Arc::clone(&per_task_memory_pool.memory_pool)
-        }
-        MemoryPoolType::Greedy => Arc::new(TrackConsumersPool::new(
-            GreedyMemoryPool::new(memory_pool_config.pool_size),
-            NonZeroUsize::new(NUM_TRACKED_CONSUMERS).unwrap(),
-        )),
-        MemoryPoolType::FairSpill => Arc::new(TrackConsumersPool::new(
-            FairSpillPool::new(memory_pool_config.pool_size),
+
+    fn tracked(pool: impl MemoryPool + 'static) -> Arc<dyn MemoryPool> {
+        Arc::new(TrackConsumersPool::new(
+            pool,
             NonZeroUsize::new(NUM_TRACKED_CONSUMERS).unwrap(),
-        )),
+        ))
+    }
+
+    let pool_type = memory_pool_config.pool_type;
+    let pool_size = memory_pool_config.pool_size;
+
+    match pool_type {
+        MemoryPoolType::GreedyUnified => acquire_task_shared_pool(task_attempt_id, || {
+            tracked(CometUnifiedMemoryPool::new(
+                comet_task_memory_manager,
+                task_attempt_id,
+            ))
+        }),
+        MemoryPoolType::FairUnified => acquire_task_shared_pool(task_attempt_id, || {
+            tracked(CometFairMemoryPool::new(
+                comet_task_memory_manager,
+                pool_size,
+            ))
+        }),
+        MemoryPoolType::GreedyTaskShared => acquire_task_shared_pool(task_attempt_id, || {
+            tracked(GreedyMemoryPool::new(pool_size))
+        }),
+        MemoryPoolType::FairSpillTaskShared => {
+            acquire_task_shared_pool(task_attempt_id, || tracked(FairSpillPool::new(pool_size)))
+        }
+        MemoryPoolType::Greedy => tracked(GreedyMemoryPool::new(pool_size)),
+        MemoryPoolType::FairSpill => tracked(FairSpillPool::new(pool_size)),
         MemoryPoolType::GreedyGlobal => {
             static GLOBAL_MEMORY_POOL_GREEDY: OnceCell<Arc<dyn MemoryPool>> = OnceCell::new();
-            let memory_pool = GLOBAL_MEMORY_POOL_GREEDY.get_or_init(|| {
-                Arc::new(TrackConsumersPool::new(
-                    GreedyMemoryPool::new(memory_pool_config.pool_size),
-                    NonZeroUsize::new(NUM_TRACKED_CONSUMERS).unwrap(),
-                ))
-            });
+            let memory_pool =
+                GLOBAL_MEMORY_POOL_GREEDY.get_or_init(|| tracked(GreedyMemoryPool::new(pool_size)));
             Arc::clone(memory_pool)
         }
         MemoryPoolType::FairSpillGlobal => {
             static GLOBAL_MEMORY_POOL_FAIR: OnceCell<Arc<dyn MemoryPool>> = OnceCell::new();
-            let memory_pool = GLOBAL_MEMORY_POOL_FAIR.get_or_init(|| {
-                Arc::new(TrackConsumersPool::new(
-                    FairSpillPool::new(memory_pool_config.pool_size),
-                    NonZeroUsize::new(NUM_TRACKED_CONSUMERS).unwrap(),
-                ))
-            });
+            let memory_pool =
+                GLOBAL_MEMORY_POOL_FAIR.get_or_init(|| tracked(FairSpillPool::new(pool_size)));
             Arc::clone(memory_pool)
         }
-        MemoryPoolType::GreedyTaskShared | MemoryPoolType::FairSpillTaskShared => {
-            let mut memory_pool_map = TASK_SHARED_MEMORY_POOLS.lock().unwrap();
-            let per_task_memory_pool =
-                memory_pool_map.entry(task_attempt_id).or_insert_with(|| {
-                    let pool: Arc<dyn MemoryPool> =
-                        if memory_pool_config.pool_type == MemoryPoolType::GreedyTaskShared {
-                            Arc::new(TrackConsumersPool::new(
-                                GreedyMemoryPool::new(memory_pool_config.pool_size),
-                                NonZeroUsize::new(NUM_TRACKED_CONSUMERS).unwrap(),
-                            ))
-                        } else {
-                            Arc::new(TrackConsumersPool::new(
-                                FairSpillPool::new(memory_pool_config.pool_size),
-                                NonZeroUsize::new(NUM_TRACKED_CONSUMERS).unwrap(),
-                            ))
-                        };
-                    PerTaskMemoryPool::new(pool)
-                });
-            per_task_memory_pool.num_plans += 1;
-            Arc::clone(&per_task_memory_pool.memory_pool)
-        }
         MemoryPoolType::Unbounded => Arc::new(UnboundedMemoryPool::default()),
     }
 }
diff --git a/native/core/src/execution/memory_pools/task_shared.rs b/native/core/src/execution/memory_pools/task_shared.rs
index 01bbce2bb3..b5b4da61f9 100644
--- a/native/core/src/execution/memory_pools/task_shared.rs
+++ b/native/core/src/execution/memory_pools/task_shared.rs
@@ -15,46 +15,204 @@
 // specific language governing permissions and limitations
 // under the License.
 
-use crate::execution::memory_pools::MemoryPoolType;
-use datafusion::execution::memory_pool::MemoryPool;
+use datafusion::execution::memory_pool::{
+    MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation,
+};
 use once_cell::sync::Lazy;
+use parking_lot::Mutex;
+use std::collections::hash_map::Entry;
 use std::collections::HashMap;
-use std::sync::{Arc, Mutex};
+use std::fmt;
+use std::sync::{Arc, Weak};
 
-/// The per-task memory pools keyed by task attempt id.
-pub(crate) static TASK_SHARED_MEMORY_POOLS: Lazy<Mutex<HashMap<i64, PerTaskMemoryPool>>> =
+/// The memory pools for active task attempts. Weak references let the pool's normal `Arc`
+/// ownership determine its lifetime, and each pool removes its entry when the last reference drops.
+static TASK_SHARED_MEMORY_POOLS: Lazy<Mutex<HashMap<i64, Weak<TaskSharedMemoryPool>>>> =
     Lazy::new(|| Mutex::new(HashMap::new()));
 
-pub(crate) struct PerTaskMemoryPool {
-    pub(crate) memory_pool: Arc<dyn MemoryPool>,
-    pub(crate) num_plans: usize,
+/// A transparent `MemoryPool` wrapper whose lifetime also controls its registry entry.
+#[derive(Debug)]
+struct TaskSharedMemoryPool {
+    task_attempt_id: i64,
+    inner: Arc<dyn MemoryPool>,
 }
 
-impl PerTaskMemoryPool {
-    pub(crate) fn new(memory_pool: Arc<dyn MemoryPool>) -> Self {
-        Self {
-            memory_pool,
-            num_plans: 0,
+impl fmt::Display for TaskSharedMemoryPool {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        fmt::Display::fmt(self.inner.as_ref(), f)
+    }
+}
+
+impl MemoryPool for TaskSharedMemoryPool {
+    fn name(&self) -> &str {
+        self.inner.name()
+    }
+
+    fn register(&self, consumer: &MemoryConsumer) {
+        self.inner.register(consumer)
+    }
+
+    fn unregister(&self, consumer: &MemoryConsumer) {
+        self.inner.unregister(consumer)
+    }
+
+    fn grow(&self, reservation: &MemoryReservation, additional: usize) {
+        self.inner.grow(reservation, additional)
+    }
+
+    fn shrink(&self, reservation: &MemoryReservation, shrink: usize) {
+        self.inner.shrink(reservation, shrink)
+    }
+
+    fn try_grow(
+        &self,
+        reservation: &MemoryReservation,
+        additional: usize,
+    ) -> datafusion::common::Result<()> {
+        self.inner.try_grow(reservation, additional)
+    }
+
+    fn reserved(&self) -> usize {
+        self.inner.reserved()
+    }
+
+    fn memory_limit(&self) -> MemoryLimit {
+        self.inner.memory_limit()
+    }
+}
+
+impl Drop for TaskSharedMemoryPool {
+    fn drop(&mut self) {
+        if let Entry::Occupied(entry) = TASK_SHARED_MEMORY_POOLS.lock().entry(self.task_attempt_id)
+        {
+            // An acquire racing with this drop can replace our expired `Weak` before we obtain the
+            // lock. Do not let the old pool remove that replacement's entry.
+            if std::ptr::eq(entry.get().as_ptr(), self) {
+                entry.remove();
+            }
         }
     }
 }
 
-// This function reduces the refcount of a per-task memory pool when a native plan is released.
-// If the refcount reaches zero, the memory pool is removed from the map and dropped.
-pub(crate) fn handle_task_shared_pool_release(pool_type: MemoryPoolType, task_attempt_id: i64) {
-    if !pool_type.is_task_shared() {
-        return;
-    }
-
-    // Decrement the number of native plans using the per-task shared memory pool, and
-    // remove the memory pool if the released native plan is the last native plan using it.
-    let mut memory_pool_map = TASK_SHARED_MEMORY_POOLS.lock().unwrap();
-    if let Some(per_task_memory_pool) = memory_pool_map.get_mut(&task_attempt_id) {
-        per_task_memory_pool.num_plans -= 1;
-        if per_task_memory_pool.num_plans == 0 {
-            // Drop the memory pool from the per-task memory pool map if there are no
-            // more native plans using it.
-            memory_pool_map.remove(&task_attempt_id);
+/// Returns the memory pool shared by every native plan in `task_attempt_id`, creating it with
+/// `create` if no live pool exists for the task. The returned `Arc` is the RAII handle: the pool
+/// stays registered until the last reference to it drops.
+pub(crate) fn acquire_task_shared_pool(
+    task_attempt_id: i64,
+    create: impl FnOnce() -> Arc<dyn MemoryPool>,
+) -> Arc<dyn MemoryPool> {
+    let mut memory_pool_map = TASK_SHARED_MEMORY_POOLS.lock();
+    if let Some(memory_pool) = memory_pool_map
+        .get(&task_attempt_id)
+        .and_then(Weak::upgrade)
+    {
+        return memory_pool;
+    }
+
+    let memory_pool = Arc::new(TaskSharedMemoryPool {
+        task_attempt_id,
+        inner: create(),
+    });
+    memory_pool_map.insert(task_attempt_id, Arc::downgrade(&memory_pool));
+    memory_pool
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use datafusion::execution::memory_pool::UnboundedMemoryPool;
+
+    /// Tests share the process-wide pool map, so each uses its own task attempt id.
+    fn acquire(task_attempt_id: i64) -> Arc<dyn MemoryPool> {
+        acquire_task_shared_pool(task_attempt_id, || Arc::new(UnboundedMemoryPool::default()))
+    }
+
+    fn is_registered(task_attempt_id: i64) -> bool {
+        TASK_SHARED_MEMORY_POOLS
+            .lock()
+            .contains_key(&task_attempt_id)
+    }
+
+    #[test]
+    fn plans_in_the_same_task_share_one_pool() {
+        let first = acquire(-1001);
+        let second = acquire(-1001);
+        assert!(Arc::ptr_eq(&first, &second));
+    }
+
+    #[test]
+    fn plans_in_different_tasks_get_different_pools() {
+        let first = acquire(-1002);
+        let second = acquire(-1003);
+        assert!(!Arc::ptr_eq(&first, &second));
+    }
+
+    #[test]
+    fn pool_is_removed_only_after_the_last_reference_drops() {
+        let first = acquire(-1004);
+        let second = acquire(-1004);
+
+        drop(first);
+        assert!(
+            is_registered(-1004),
+            "pool must outlive the first reference to release it"
+        );
+
+        drop(second);
+        assert!(!is_registered(-1004));
+    }
+
+    #[test]
+    fn dropping_the_reference_releases_the_pool() {
+        // Stands in for `createPlan` failing after the pool was acquired. The ordinary `Arc` drops
+        // on unwind, so no explicit release path is needed.
+        {
+            let _pool = acquire(-1005);
+            assert!(is_registered(-1005));
         }
+        assert!(!is_registered(-1005));
+    }
+
+    #[test]
+    fn an_old_pool_does_not_remove_its_replacement() {
+        let old_pool = acquire(-1006);
+        TASK_SHARED_MEMORY_POOLS.lock().remove(&-1006);
+        let replacement = acquire(-1006);
+
+        drop(old_pool);
+        assert!(is_registered(-1006));
+
+        drop(replacement);
+        assert!(!is_registered(-1006));
+    }
+
+    /// Exercises the drop/acquire race for real: an acquire can replace an expired `Weak` between
+    /// another thread's last `Arc` drop and that drop obtaining the registry lock, and the old
+    /// pool's `Drop` must not evict the replacement's entry.
+    #[test]
+    fn concurrent_acquire_and_drop_leaves_a_consistent_registry() {
+        use std::thread;
+
+        let threads: Vec<_> = (0..8)
+            .map(|_| {
+                thread::spawn(|| {
+                    for _ in 0..1_000 {
+                        drop(acquire(-1007));
+                    }
+                })
+            })
+            .collect();
+        for thread in threads {
+            thread.join().unwrap();
+        }
+
+        assert!(
+            !is_registered(-1007),
+            "registry entry survived after every reference was dropped"
+        );
+
+        // The registry must still work for the task after the churn.
+        let _pool = acquire(-1007);
+        assert!(is_registered(-1007));
     }
 }
diff --git a/spark/src/main/scala/org/apache/comet/CometExecIterator.scala b/spark/src/main/scala/org/apache/comet/CometExecIterator.scala
index 17d78dfee7..e2c132904d 100644
--- a/spark/src/main/scala/org/apache/comet/CometExecIterator.scala
+++ b/spark/src/main/scala/org/apache/comet/CometExecIterator.scala
@@ -274,24 +274,54 @@ class CometExecIterator(
 
   def close(): Unit = synchronized {
     if (!closed) {
-      if (currentBatch != null) {
-        currentBatch.close()
-        currentBatch = null
+      closed = true
+
+      // Attempt every resource's cleanup independently, so that one failure does not skip the
+      // remaining resources: this close() is the only chance to release them, since `closed` is
+      // already set and the task-completion retry is a no-op. The first failure is rethrown with
+      // any later ones attached as suppressed exceptions.
+      var failure: Throwable = null
+      def attempt(cleanup: => Unit): Unit = {
+        try {
+          cleanup
+        } catch {
+          case t: Throwable =>
+            if (failure == null) failure = t else failure.addSuppressed(t)
+        }
       }
-      nativeUtil.close()
-      shuffleBlockIterators.values.foreach(_.close())
-      nativeLib.releasePlan(plan)
 
-      if (tracingEnabled) {
-        traceMemoryUsage()
+      attempt {
+        if (currentBatch != null) {
+          currentBatch.close()
+          currentBatch = null
+        }
+      }
+      attempt(nativeUtil.close())
+      shuffleBlockIterators.values.foreach(it => attempt(it.close()))
+
+      // Released last and exactly once, even if the teardown above failed: dropping the native
+      // execution context frees this plan's task-shared memory pool reference and several JNI
+      // global refs.
+      attempt(nativeLib.releasePlan(plan))
+
+      // Run the diagnostics even when teardown failed: a failed teardown is exactly when the
+      // non-zero memory usage warning below is most informative.
+      attempt {
+        if (tracingEnabled) {
+          traceMemoryUsage()
+        }
       }
 
-      val memInUse = cometTaskMemoryManager.getUsed
-      if (memInUse != 0) {
-        logWarning(s"CometExecIterator closed with non-zero memory usage : $memInUse")
+      attempt {
+        val memInUse = cometTaskMemoryManager.getUsed
+        if (memInUse != 0) {
+          logWarning(s"CometExecIterator closed with non-zero memory usage : $memInUse")
+        }
       }
 
-      closed = true
+      if (failure != null) {
+        throw failure
+      }
     }
   }
 
diff --git a/spark/src/test/scala/org/apache/spark/CometExecIteratorLifecycleSuite.scala b/spark/src/test/scala/org/apache/spark/CometExecIteratorLifecycleSuite.scala
new file mode 100644
index 0000000000..a5b98dd598
--- /dev/null
+++ b/spark/src/test/scala/org/apache/spark/CometExecIteratorLifecycleSuite.scala
@@ -0,0 +1,223 @@
+/*
+ * 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.ByteArrayInputStream
+import java.lang.ref.WeakReference
+import java.util.Properties
+import java.util.concurrent.atomic.AtomicBoolean
+
+import org.apache.spark.executor.TaskMetrics
+import org.apache.spark.memory.{TaskMemoryManager, TestMemoryManager}
+import org.apache.spark.sql.CometTestBase
+import org.apache.spark.sql.catalyst.expressions.PrettyAttribute
+import org.apache.spark.sql.comet.{CometExec, CometExecUtils, CometMetricNode}
+import org.apache.spark.sql.comet.execution.arrow.CometArrowStream
+import org.apache.spark.sql.types.{LongType, StructField, StructType}
+
+import org.apache.comet.{CometConf, CometExecIterator, CometShuffleBlockIterator, Native}
+import org.apache.comet.serde.Config.ConfigMap
+import org.apache.comet.serde.OperatorOuterClass
+
+/**
+ * Regression tests for the native plan lifecycle: every `createPlan` must be balanced by exactly
+ * one release of the native execution context and of its task-shared memory pool reference, even
+ * when a step of the lifecycle fails partway through. See issue #5212 (positions 2, 3 and 8).
+ */
+class CometExecIteratorLifecycleSuite extends CometTestBase {
+
+  private def withTaskContext[T](taskAttemptId: Long)(f: => T): T = {
+    val memoryManager = new TestMemoryManager(new SparkConf())
+    val taskMemoryManager = new TaskMemoryManager(memoryManager, taskAttemptId)
+    val taskContext = new TaskContextImpl(
+      stageId = 0,
+      stageAttemptNumber = 0,
+      partitionId = 0,
+      numPartitions = 1,
+      taskAttemptId = taskAttemptId,
+      attemptNumber = 0,
+      taskMemoryManager = taskMemoryManager,
+      localProperties = new Properties,
+      metricsSystem = null,
+      taskMetrics = TaskMetrics.empty,
+      cpus = 1,
+      resources = Map.empty)
+    TaskContext.setTaskContext(taskContext)
+    try {
+      f
+    } finally {
+      taskMemoryManager.cleanUpAllAllocatedMemory()
+      TaskContext.unset()
+    }
+  }
+
+  /** Retries GC until every weak reference clears or the deadline passes; returns survivors. */
+  private def survivorsAfterGc(refs: Seq[WeakReference[_]]): Int = {
+    val deadline = System.nanoTime() + 30L * 1000 * 1000 * 1000
+    while (refs.exists(_.get() != null) && System.nanoTime() < deadline) {
+      System.gc()
+      Thread.sleep(50)
+    }
+    refs.count(_.get() != null)
+  }
+
+  test("createPlan failure releases the task-shared memory pool reference") {
+    val nativeLib = new Native()
+    val emptyPlan = OperatorOuterClass.Operator.newBuilder().build().toByteArray
+    // An unknown DataFusion config makes createPlan fail while building the session context,
+    // which happens after the task-shared memory pool has been registered for the task.
+    val badConfigs = ConfigMap
+      .newBuilder()
+      .putEntries("spark.comet.datafusion.no_such_namespace.option", "1")
+      .build()
+      .toByteArray
+
+    val managerRefs = (0 until 10).map { i =>
+      // Unique synthetic task attempt ids keep each iteration's pool entry independent.
+      val taskAttemptId = 4200000L + i
+      withTaskContext(taskAttemptId) {
+        val manager = new CometTaskMemoryManager(i, taskAttemptId)
+        val thrown = intercept[Throwable] {
+          nativeLib.createPlan(
+            i,
+            Array.empty[Object],
+            emptyPlan,
+            badConfigs,
+            1,
+            CometMetricNode(Map.empty),
+            0L,
+            manager,
+            Array(System.getProperty("java.io.tmpdir")),
+            8192,
+            true,
+            "fair_unified",
+            64L << 20,
+            64L << 20,
+            taskAttemptId,
+            1L,
+            null,
+            null,
+            null)
+        }
+        // Guard against a vacuous pass: the failure must be the injected config error thrown
+        // inside createPlan, not e.g. an UnsatisfiedLinkError from a missing native library.
+        assert(
+          thrown.getMessage != null && thrown.getMessage.contains("no_such_namespace"),
+          s"expected the injected DataFusion config failure, got: $thrown")
+        new WeakReference(manager)
+      }
+    }
+
+    // A stranded TASK_SHARED_MEMORY_POOLS entry holds a JNI global ref to the
+    // CometTaskMemoryManager, so the manager staying reachable means the pool leaked.
+    val survivors = survivorsAfterGc(managerRefs)
+    assert(
+      survivors == 0,
+      s"$survivors of ${managerRefs.size} CometTaskMemoryManagers stayed reachable: " +
+        "createPlan failure leaked their task-shared memory pool references")
+  }
+
+  test("close() is idempotent and still releases the plan when teardown throws") {
+    withTaskContext(4300000L) {
+      val boom = new java.io.IOException("injected shuffle block close failure")
+      val throwingBlockIter =
+        new CometShuffleBlockIterator(new ByteArrayInputStream(Array.emptyByteArray)) {
+          override def close(): Unit = throw boom
+        }
+      @volatile var laterInputClosed = false
+      val trackingBlockIter =
+        new CometShuffleBlockIterator(new ByteArrayInputStream(Array.emptyByteArray)) {
+          override def close(): Unit = {
+            laterInputClosed = true
+            super.close()
+          }
+        }
+      val limitOp =
+        CometExecUtils.getLimitNativePlan(Seq(PrettyAttribute("test", LongType)), 100).get
+      val iter = new CometExecIterator(
+        id = 1L,
+        inputObjects = Array.empty[Object],
+        numOutputCols = 1,
+        protobufQueryPlan = limitOp.toByteArray,
+        nativeMetrics = CometMetricNode(Map.empty),
+        numParts = 1,
+        partitionIndex = 0,
+        shuffleBlockIterators = Map(0 -> throwingBlockIter, 1 -> trackingBlockIter))
+
+      val thrown = intercept[java.io.IOException](iter.close())
+      assert(thrown eq boom)
+      // One input's close failure must not skip the remaining resources: this close() is the only
+      // chance to release them, since the task-completion retry is a no-op once `closed` is set.
+      assert(laterInputClosed, "a later shuffle input was not closed after an earlier one threw")
+      // The first close() must have marked the iterator closed and released the plan despite the
+      // teardown failure: a second close() re-running releasePlan would free the native
+      // execution context twice, and skipping the release would strand it.
+      iter.close()
+    }
+  }
+
+  test("releasePlan frees the native context even when the final metrics update fails") {
+    // Disable the periodic metrics updates inside executePlan, so the only metrics update -- and
+    // therefore the only place the injected failure can fire -- is the one in releasePlan.
+    withSQLConf(CometConf.COMET_METRICS_UPDATE_INTERVAL.key -> "0") {
+      withTaskContext(4400000L) {
+        val failMetrics = new AtomicBoolean(false)
+        class ThrowingMetricNode extends CometMetricNode(Map.empty, Nil) {
+          override def set_all_from_bytes(bytes: Array[Byte]): Unit = {
+            if (failMetrics.get()) {
+              throw new IllegalStateException("injected metrics update failure")
+            }
+          }
+        }
+        val schema = StructType(Seq(StructField("test", LongType, nullable = false)))
+        val stream = CometArrowStream.fromColumnarBatchIter(
+          Iterator.empty,
+          schema,
+          CometArrowStream.NATIVE_TIMEZONE,
+          "lifecycle-test")
+        val limitOp =
+          CometExecUtils.getLimitNativePlan(Seq(PrettyAttribute("test", LongType)), 100).get
+        val iter = CometExec.getCometIterator(
+          Array(stream.asInstanceOf[Object]),
+          1,
+          limitOp,
+          new ThrowingMetricNode,
+          1,
+          0,
+          None,
+          Seq.empty)
+
+        failMetrics.set(true)
+        // Exhausting the iterator closes it, and the close propagates the metrics failure thrown
+        // by the native releasePlan call.
+        val thrown = intercept[Throwable](iter.hasNext)
+        // Guard against a vacuous pass: the failure must be the injected one, thrown from the
+        // releasePlan metrics update (the only metrics update left with the interval disabled).
+        assert(
+          thrown.getMessage != null && thrown.getMessage.contains(
+            "injected metrics update failure"),
+          s"expected the injected metrics update failure, got: $thrown")
+        // The metrics failure must not have left the iterator open or the native context alive: a
+        // second close() must be a no-op instead of calling releasePlan again.
+        iter.close()
+      }
+    }
+  }
+}


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