Copilot commented on code in PR #13728:
URL: https://github.com/apache/gluten/pull/13728#discussion_r4685662324


##########
cpp/core/tests/JniThreadExitTest.cc:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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 <gtest/gtest.h>
+#include <pthread.h>
+
+#include <thread>
+
+#include "jni/JniCommon.h"
+#include "tests/utils/TestJniEnvironment.h"
+
+using namespace gluten;
+
+namespace {
+
+JavaVM* vmOf(TestJniEnvironment& jni) {
+  JavaVM* vm = nullptr;
+  jni.env()->GetJavaVM(&vm);
+  return vm;
+}
+
+void glutenAttach(JavaVM* vm) {
+  JNIEnv* env = nullptr;
+  attachCurrentThreadAsDaemonOrThrow(vm, &env);
+  ASSERT_NE(env, nullptr);
+}
+
+// Mirrors libhdfs: it caches the thread's JNIEnv* in a pthread key and, from 
that key's destructor
+// at thread exit, still uses the JNIEnv* and then detaches the thread 
(hdfsThreadDestructor).
+struct HdfsLikeState {
+  TestJniEnvironment* jni{nullptr};
+  bool attachedWhenDestructorRan{false};
+};
+
+void hdfsLikeDestructor(void* value) {
+  auto* state = static_cast<HdfsLikeState*>(value);
+  state->attachedWhenDestructorRan = state->jni->workerAttached;
+  vmOf(*state->jni)->DetachCurrentThread();
+}
+
+pthread_key_t createHdfsLikeKey() {
+  pthread_key_t key;
+  EXPECT_EQ(pthread_key_create(&key, hdfsLikeDestructor), 0);
+  return key;
+}
+
+// Created during static initialization, so before Gluten's key: its 
destructor runs first in each round.
+const pthread_key_t hdfsKeyCreatedBeforeGluten = createHdfsLikeKey();

Review Comment:
   `EXPECT_EQ` is a gtest assertion macro and is not safe to run during static 
initialization (here it executes before tests are initialized). This can lead 
to undefined behavior / missing failures depending on runner initialization 
order. Make key creation occur inside a test/fixture setup using `ASSERT_*`, or 
replace the global initialization path with non-gtest error handling (e.g., 
check rc and `std::terminate()`/`CHECK_EQ`) and avoid gtest macros outside test 
bodies.



##########
cpp/core/tests/JniThreadExitTest.cc:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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 <gtest/gtest.h>
+#include <pthread.h>
+
+#include <thread>
+
+#include "jni/JniCommon.h"
+#include "tests/utils/TestJniEnvironment.h"
+
+using namespace gluten;
+
+namespace {
+
+JavaVM* vmOf(TestJniEnvironment& jni) {
+  JavaVM* vm = nullptr;
+  jni.env()->GetJavaVM(&vm);
+  return vm;
+}
+
+void glutenAttach(JavaVM* vm) {
+  JNIEnv* env = nullptr;
+  attachCurrentThreadAsDaemonOrThrow(vm, &env);
+  ASSERT_NE(env, nullptr);
+}
+
+// Mirrors libhdfs: it caches the thread's JNIEnv* in a pthread key and, from 
that key's destructor
+// at thread exit, still uses the JNIEnv* and then detaches the thread 
(hdfsThreadDestructor).
+struct HdfsLikeState {
+  TestJniEnvironment* jni{nullptr};
+  bool attachedWhenDestructorRan{false};
+};
+
+void hdfsLikeDestructor(void* value) {
+  auto* state = static_cast<HdfsLikeState*>(value);
+  state->attachedWhenDestructorRan = state->jni->workerAttached;
+  vmOf(*state->jni)->DetachCurrentThread();
+}
+
+pthread_key_t createHdfsLikeKey() {
+  pthread_key_t key;
+  EXPECT_EQ(pthread_key_create(&key, hdfsLikeDestructor), 0);
+  return key;
+}
+
+// Created during static initialization, so before Gluten's key: its 
destructor runs first in each round.
+const pthread_key_t hdfsKeyCreatedBeforeGluten = createHdfsLikeKey();
+
+void runHdfsAfterGlutenAttach(pthread_key_t hdfsKey) {
+  TestJniEnvironment jni;
+  HdfsLikeState state{&jni};
+  std::thread worker([&] {
+    glutenAttach(vmOf(jni));
+    pthread_setspecific(hdfsKey, &state); // libhdfs then uses the 
already-attached thread.
+  });
+  worker.join();
+  EXPECT_TRUE(state.attachedWhenDestructorRan); // libhdfs never sees a 
detached thread.
+  EXPECT_EQ(jni.attaches, 1);
+  EXPECT_EQ(jni.detaches, 1); // only libhdfs detached it.
+  EXPECT_FALSE(jni.workerAttached);
+}
+
+} // namespace
+
+TEST(JniThreadExitTest, detachesThreadAttachedByGlutenOnExit) {
+  TestJniEnvironment jni;
+  std::thread worker([&] { glutenAttach(vmOf(jni)); });
+  worker.join();
+  EXPECT_EQ(jni.attaches, 1);
+  EXPECT_EQ(jni.detaches, 1);
+  EXPECT_FALSE(jni.workerAttached);
+}
+
+TEST(JniThreadExitTest, doesNotDetachThreadAttachedElsewhere) {
+  TestJniEnvironment jni;
+  jni.workerAttached = true; // e.g. a Java-created thread, or one Java or 
libhdfs attached first.
+  std::thread worker([&] { glutenAttach(vmOf(jni)); });
+  worker.join();
+  EXPECT_EQ(jni.attaches, 0);
+  EXPECT_EQ(jni.detaches, 0);
+  EXPECT_TRUE(jni.workerAttached);
+}
+
+TEST(JniThreadExitTest, detachesOnceWhenHelperIsCalledRepeatedly) {
+  TestJniEnvironment jni;
+  std::thread worker([&] {
+    for (int i = 0; i < 3; ++i) {
+      glutenAttach(vmOf(jni));
+    }
+  });
+  worker.join();
+  EXPECT_EQ(jni.attaches, 1);
+  EXPECT_EQ(jni.detaches, 1);
+}
+
+TEST(JniThreadExitTest, detachesReattachedThreadOnExit) {
+  TestJniEnvironment jni;
+  std::thread worker([&] {
+    glutenAttach(vmOf(jni));
+    vmOf(jni)->DetachCurrentThread();
+    glutenAttach(vmOf(jni));
+  });
+  worker.join();
+  EXPECT_EQ(jni.attaches, 2);
+  EXPECT_EQ(jni.detaches, 2); // one explicit detach, one at thread exit.
+  EXPECT_FALSE(jni.workerAttached);
+}
+
+TEST(JniThreadExitTest, libhdfsDestructorRunsFirstWhenItsKeyIsOlder) {
+  runHdfsAfterGlutenAttach(hdfsKeyCreatedBeforeGluten);
+}
+
+TEST(JniThreadExitTest, libhdfsDestructorRunsFirstWhenItsKeyIsNewer) {
+  {
+    // Make sure Gluten's key exists before creating the libhdfs-like key.
+    TestJniEnvironment jni;
+    std::thread worker([&] { glutenAttach(vmOf(jni)); });
+    worker.join();
+  }
+  runHdfsAfterGlutenAttach(createHdfsLikeKey());
+}

Review Comment:
   `createHdfsLikeKey()` allocates pthread keys that are never deleted; 
repeated runs (or future additions) can exhaust `PTHREAD_KEYS_MAX` and cause 
confusing failures. In tests, prefer an RAII wrapper (or a fixture) that calls 
`pthread_key_delete` after the test, and avoid using a process-lifetime global 
key unless necessary.



##########
cpp/core/tests/JniThreadExitTest.cc:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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 <gtest/gtest.h>
+#include <pthread.h>
+
+#include <thread>
+
+#include "jni/JniCommon.h"
+#include "tests/utils/TestJniEnvironment.h"
+
+using namespace gluten;
+
+namespace {
+
+JavaVM* vmOf(TestJniEnvironment& jni) {
+  JavaVM* vm = nullptr;
+  jni.env()->GetJavaVM(&vm);
+  return vm;
+}
+
+void glutenAttach(JavaVM* vm) {
+  JNIEnv* env = nullptr;
+  attachCurrentThreadAsDaemonOrThrow(vm, &env);
+  ASSERT_NE(env, nullptr);
+}
+
+// Mirrors libhdfs: it caches the thread's JNIEnv* in a pthread key and, from 
that key's destructor
+// at thread exit, still uses the JNIEnv* and then detaches the thread 
(hdfsThreadDestructor).
+struct HdfsLikeState {
+  TestJniEnvironment* jni{nullptr};
+  bool attachedWhenDestructorRan{false};
+};
+
+void hdfsLikeDestructor(void* value) {
+  auto* state = static_cast<HdfsLikeState*>(value);
+  state->attachedWhenDestructorRan = state->jni->workerAttached;
+  vmOf(*state->jni)->DetachCurrentThread();
+}
+
+pthread_key_t createHdfsLikeKey() {
+  pthread_key_t key;
+  EXPECT_EQ(pthread_key_create(&key, hdfsLikeDestructor), 0);
+  return key;
+}
+
+// Created during static initialization, so before Gluten's key: its 
destructor runs first in each round.
+const pthread_key_t hdfsKeyCreatedBeforeGluten = createHdfsLikeKey();

Review Comment:
   `createHdfsLikeKey()` allocates pthread keys that are never deleted; 
repeated runs (or future additions) can exhaust `PTHREAD_KEYS_MAX` and cause 
confusing failures. In tests, prefer an RAII wrapper (or a fixture) that calls 
`pthread_key_delete` after the test, and avoid using a process-lifetime global 
key unless necessary.



##########
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.

Review Comment:
   The implementation assumes a single JVM per process (it stores `JavaVM*` in 
a global atomic rather than per-thread TSD). That’s a reasonable HotSpot/JNI 
constraint, but it’s part of the API contract—please document the 
“single-JVM-per-process” assumption here in the header docstring (not only in 
the `.cc`) so callers understand the limitation.



##########
cpp/core/jni/JniThreadExit.cc:
##########
@@ -0,0 +1,93 @@
+/*
+ * 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;
+
+// The VM to detach from. The destructor only receives the TSD value (kArmed 
or kDeferred), so it reads
+// the VM from here. Every registration stores the same pointer, since a 
process has one JVM; the
+// atomic only avoids a data race between registering threads and exiting 
threads.
+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.
+//
+// A C++ thread_local destructor cannot replace this key: glibc runs all 
thread_local destructors
+// before any pthread TSD destructor, so the detach would always precede 
libhdfs's destructor and
+// bring back the GLUTEN-11895 crash for threads that libhdfs uses.
+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;
+  // JNI_VERSION_1_8 is the JNI interface version requested from GetEnv, the 
same one Gluten uses
+  // everywhere; every JDK from 8 on supports it, so this check applies to all 
JDKs. It only asks
+  // whether the thread is still attached: JNI_EDETACHED means libhdfs already 
detached it.
+  if (vm != nullptr && vm->GetEnv(reinterpret_cast<void**>(&env), 
JNI_VERSION_1_8) == JNI_OK) {
+    vm->DetachCurrentThread();
+  }

Review Comment:
   After the deferred round runs, the TSD value is left non-null (`kDeferred`), 
so POSIX/glibc will re-invoke the destructor for this key in subsequent rounds 
(up to `PTHREAD_DESTRUCTOR_ITERATIONS`). This causes redundant `GetEnv` calls 
on thread exit. Consider clearing the key (set the TSD value to `nullptr`) once 
the deferred path executes (regardless of whether detach was needed) to ensure 
only the intended two invocations occur.



##########
cpp/core/jni/JniThreadExit.cc:
##########
@@ -0,0 +1,93 @@
+/*
+ * 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;
+
+// The VM to detach from. The destructor only receives the TSD value (kArmed 
or kDeferred), so it reads
+// the VM from here. Every registration stores the same pointer, since a 
process has one JVM; the
+// atomic only avoids a data race between registering threads and exiting 
threads.

Review Comment:
   Using small integers converted to `void*` as pthread TSD values is 
implementation-defined and can be problematic on less common 
architectures/ABIs. A more portable approach is to store the address of 
distinct static tag objects (e.g., `&armedTag` / `&deferredTag`) or store a 
pointer to a small per-thread state struct that includes both the stage and the 
`JavaVM*`.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to