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

philo-he pushed a commit to branch fix-detach-native-threads-on-exit
in repository https://gitbox.apache.org/repos/asf/gluten.git

commit 0a7dd3418f127ed48b2f3515f212095524af67ae
Author: Philo He <[email protected]>
AuthorDate: Mon Nov 23 04:07:07 2026 +0000

    [VL] Detach Gluten-attached native threads from the JVM when they exit
    
    Native threads that Gluten attaches to the JVM (Velox IO, spill and 
broadcast
    hash-table build pool workers, which attach lazily through
    SparkAllocationListener) were never detached. folly pools retire idle 
workers
    after --threadtimeout_ms (60s), so these threads exit while the executor 
runs
    and leave a JavaThread behind for a pthread that no longer exists. The next
    walk of the JVM thread list (jstack/jcmd Thread.print, JVMTI agents, 
profilers,
    EMR instance-state log collection) then crashes the executor with SIGSEGV in
    pthread_getcpuclockid.
    
    attachCurrentThreadAsDaemonOrThrow now registers a pthread TSD destructor 
for
    every thread it attaches. The destructor defers itself by one destructor 
round
    before calling DetachCurrentThread, so libhdfs's own thread-exit destructor,
    which still dereferences its cached JNIEnv*, always runs first. Threads 
used by
    libhdfs are therefore left for libhdfs to detach, and the HDFS crash fixed 
in
    GLUTEN-11895 cannot come back. Mid-life detaching is still never done.
---
 cpp/core/CMakeLists.txt       |  1 +
 cpp/core/jni/JniCommon.h      |  3 ++
 cpp/core/jni/JniThreadExit.cc | 83 +++++++++++++++++++++++++++++++++++++++++++
 cpp/core/jni/JniThreadExit.h  | 36 +++++++++++++++++++
 4 files changed, 123 insertions(+)

diff --git a/cpp/core/CMakeLists.txt b/cpp/core/CMakeLists.txt
index 6033bc3848..cf6227bc50 100644
--- a/cpp/core/CMakeLists.txt
+++ b/cpp/core/CMakeLists.txt
@@ -149,6 +149,7 @@ set(SPARK_COLUMNAR_PLUGIN_SRCS
     jni/JavaException.cc
     jni/JniError.cc
     jni/JniCommon.cc
+    jni/JniThreadExit.cc
     jni/TaskContextJniWrapper.cc)
 
 file(MAKE_DIRECTORY ${root_directory}/releases)
diff --git a/cpp/core/jni/JniCommon.h b/cpp/core/jni/JniCommon.h
index b72fd3eee9..a3fa643a99 100644
--- a/cpp/core/jni/JniCommon.h
+++ b/cpp/core/jni/JniCommon.h
@@ -27,6 +27,7 @@
 #include "JavaException.h"
 #include "compute/ProtobufUtils.h"
 #include "compute/Runtime.h"
+#include "jni/JniThreadExit.h"
 #include "memory/AllocationListener.h"
 #include "shuffle/ShuffleReader.h"
 #include "shuffle/rss/RssClient.h"
@@ -114,6 +115,8 @@ static inline void 
attachCurrentThreadAsDaemonOrThrow(JavaVM* vm, JNIEnv** out)
     if (getEnvStat != JNI_OK) {
       throw gluten::GlutenException("Failed to reattach current thread to 
JVM.");
     }
+    // Detach when this native thread exits, so the JVM is not left with a 
JavaThread for a dead pthread.
+    gluten::detachCurrentThreadOnExit(vm);
     DLOG(INFO) << "Succeeded attaching current thread.";
     return;
   }
diff --git a/cpp/core/jni/JniThreadExit.cc b/cpp/core/jni/JniThreadExit.cc
new file mode 100644
index 0000000000..9519f651db
--- /dev/null
+++ b/cpp/core/jni/JniThreadExit.cc
@@ -0,0 +1,83 @@
+/*
+ * 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.
+ */
+
+#include "jni/JniThreadExit.h"
+
+#include <pthread.h>
+
+#include <atomic>
+#include <cstdint>
+
+#include <glog/logging.h>
+
+namespace gluten {
+namespace {
+
+// The TSD value of a thread whose detach is pending. A destructor that finds 
kArmed has run in the
+// first destructor round; it re-arms with kDeferred so that it is called 
again in the next round.
+constexpr uintptr_t kArmed = 1;
+constexpr uintptr_t kDeferred = 2;
+
+std::atomic<JavaVM*> exitDetachVm{nullptr};
+pthread_key_t exitDetachKey;
+
+// Why the detach waits one destructor round:
+//
+// libhdfs caches the JNIEnv* of each thread it uses and detaches that thread 
from its own TSD
+// destructor, which still dereferences the cached JNIEnv*. If this destructor 
detached first, libhdfs
+// would use a freed JNIEnv* (the crash fixed by GLUTEN-11895, which is why 
Gluten stopped detaching
+// in its JNI helpers). POSIX re-runs TSD destructors for keys whose values 
are non-NULL again after a
+// round, and glibc does so for up to PTHREAD_DESTRUCTOR_ITERATIONS (4) 
rounds. Deferring by one round
+// means libhdfs's destructor has run, whatever its key's position, before 
this one acts: the thread
+// is then already detached (GetEnv returns JNI_EDETACHED and nothing is done) 
or libhdfs never owned
+// it and this destructor detaches it.
+//
+// Detaching from a TSD destructor is supported by HotSpot: its own TSD 
destructor restores the
+// current-thread pointer so that later destructors can still call 
DetachCurrentThread.
+void detachOnThreadExit(void* value) {
+  if (reinterpret_cast<uintptr_t>(value) == kArmed) {
+    pthread_setspecific(exitDetachKey, reinterpret_cast<void*>(kDeferred));
+    return;
+  }
+  JavaVM* vm = exitDetachVm.load(std::memory_order_acquire);
+  JNIEnv* env = nullptr;
+  if (vm != nullptr && vm->GetEnv(reinterpret_cast<void**>(&env), 
JNI_VERSION_1_8) == JNI_OK) {
+    vm->DetachCurrentThread();
+  }
+}
+
+bool createExitDetachKey() {
+  const int rc = pthread_key_create(&exitDetachKey, detachOnThreadExit);
+  if (rc != 0) {
+    LOG(WARNING) << "pthread_key_create failed with " << rc
+                 << "; native threads will stay attached to the JVM after they 
exit";
+  }
+  return rc == 0;
+}
+
+} // namespace
+
+void detachCurrentThreadOnExit(JavaVM* vm) {
+  static const bool keyCreated = createExitDetachKey();
+  if (!keyCreated) {
+    return;
+  }
+  exitDetachVm.store(vm, std::memory_order_release);
+  pthread_setspecific(exitDetachKey, reinterpret_cast<void*>(kArmed));
+}
+
+} // namespace gluten
diff --git a/cpp/core/jni/JniThreadExit.h b/cpp/core/jni/JniThreadExit.h
new file mode 100644
index 0000000000..d15eb295b0
--- /dev/null
+++ b/cpp/core/jni/JniThreadExit.h
@@ -0,0 +1,36 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include <jni.h>
+
+namespace gluten {
+
+/// Arranges for the calling native thread to be detached from `vm` when the 
thread exits.
+///
+/// Call this right after Gluten attaches a native thread to the JVM. A native 
thread that exits while
+/// still attached leaves a JavaThread whose pthread no longer exists; the 
next walk of the JVM thread
+/// list (thread dump, jcmd, JVMTI agents, profilers, EMR log collection) then 
reads that dead pthread
+/// and crashes in pthread_getcpuclockid. Native pool threads do exit while 
the executor runs, since
+/// folly pools retire idle workers after --threadtimeout_ms.
+///
+/// The detach runs from a pthread TSD destructor and is safe for threads that 
libhdfs also uses; see
+/// JniThreadExit.cc. Calling it more than once on a thread is harmless.
+void detachCurrentThreadOnExit(JavaVM* vm);
+
+} // namespace gluten


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to