philo-he commented on code in PR #13728: URL: https://github.com/apache/gluten/pull/13728#discussion_r4687479465
########## 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: Fixed in the new commit. ########## 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: These are two test-only keys that live for the duration of the test process, well under `PTHREAD_KEYS_MAX`. I'd rather keep the test simple. ########## 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: HotSpot supports only one JVM per process (`JNI_CreateJavaVM` fails for a second one), and Gluten already assumes a single `JavaVM*` in `JniCommonState`. ########## 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: `uintptr_t` ↔ `void*` round-trips are well defined on all platforms Gluten supports, and the values are only compared, never dereferenced. ########## 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: These are two test-only keys that live for the duration of the test process, well under `PTHREAD_KEYS_MAX`. I'd rather keep the test simple. ########## 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: glibc clears each TSD value before calling its destructor, so when the destructor runs in the second round with `kDeferred` and doesn't call `pthread_setspecific` again, the value is NULL afterwards and no further round runs. -- 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]
