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


##########
cpp/core/jni/JavaException.cc:
##########
@@ -0,0 +1,178 @@
+/*
+ * 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 "JavaException.h"
+
+#include <glog/logging.h>
+
+#include <stdexcept>
+#include <string>
+
+namespace gluten {
+namespace {
+
+class LocalFrame {
+ public:
+  explicit LocalFrame(JNIEnv* env) : env_(env), pushed_(env->PushLocalFrame(3) 
== JNI_OK) {}
+
+  ~LocalFrame() {
+    if (pushed_) {
+      env_->PopLocalFrame(nullptr);
+    }
+  }
+
+  bool pushed() const {
+    return pushed_;
+  }
+
+ private:
+  JNIEnv* env_;
+  bool pushed_;
+};
+
+std::string describe(JNIEnv* env, jthrowable throwable) {
+  const std::string prefix = "Error during calling Java code from native code: 
";
+  const auto unavailable = [&](const char* reason) {
+    // Describing an exception must not replace the throwable we are 
transporting.
+    env->ExceptionClear();
+    return prefix + "Java stack trace unavailable (" + reason + ")";
+  };
+  LocalFrame frame(env);
+  if (!frame.pushed()) {
+    return unavailable("PushLocalFrame failed");
+  }
+  auto describer = 
env->FindClass("org/apache/gluten/exception/JniExceptionDescriber");
+  if (describer == nullptr) {
+    return unavailable("JniExceptionDescriber lookup failed");
+  }
+  auto method = env->GetStaticMethodID(describer, "describe", 
"(Ljava/lang/Throwable;)Ljava/lang/String;");
+  if (method == nullptr) {
+    return unavailable("describe method lookup failed");
+  }
+  auto description = 
static_cast<jstring>(env->CallStaticObjectMethod(describer, method, throwable));
+  if (env->ExceptionCheck() || description == nullptr) {
+    return unavailable("describe method failed");
+  }
+  const auto release = [&](const char* chars) { 
env->ReleaseStringUTFChars(description, chars); };
+  std::unique_ptr<const char, decltype(release)> 
chars(env->GetStringUTFChars(description, nullptr), release);
+  if (!chars) {
+    return unavailable("GetStringUTFChars failed");
+  }
+  return prefix + chars.get();
+}
+
+} // namespace
+
+struct JavaException::State {
+  State(JNIEnv* env, jthrowable throwable) {
+    if (throwable == nullptr) {
+      throw std::invalid_argument("JavaException requires a non-null 
throwable");
+    }
+    if (env->GetJavaVM(&vm) != JNI_OK) {
+      throw std::runtime_error("Unable to get JavaVM for Java exception");
+    }
+    ref = static_cast<jthrowable>(env->NewGlobalRef(throwable));
+    if (ref == nullptr) {
+      throw std::runtime_error("Unable to create global reference for Java 
exception");
+    }
+  }
+
+  ~State() {
+    JNIEnv* env = nullptr;
+    auto status = vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_8);
+    const bool detached = status == JNI_EDETACHED;
+    if (detached) {
+      status = vm->AttachCurrentThreadAsDaemon(reinterpret_cast<void**>(&env), 
nullptr);
+    }

Review Comment:
   Using `JNI_VERSION_1_8` in `GetEnv` can unnecessarily reduce compatibility 
if this code ever runs with a VM that supports only older JNI versions (the 
common pattern is `JNI_VERSION_1_6`, which remains valid on newer JDKs). 
Consider switching the requested version to `JNI_VERSION_1_6` unless there’s a 
specific need for 1.8.



##########
gluten-arrow/pom.xml:
##########
@@ -278,4 +288,28 @@
     
<testOutputDirectory>target/scala-${scala.binary.version}/test-classes</testOutputDirectory>
   </build>
 
+  <profiles>
+    <profile>
+      <id>jni-test</id>
+      <properties>
+        
<gluten.jni.test.lib.dir>${project.basedir}/../cpp/build/test-libs</gluten.jni.test.lib.dir>
+      </properties>
+      <build>
+        <plugins>
+          <plugin>
+            <groupId>org.apache.maven.plugins</groupId>
+            <artifactId>maven-surefire-plugin</artifactId>
+            <configuration>
+              <excludes combine.self="override"/>
+              <failIfNoTests>true</failIfNoTests>
+              <forkedProcessTimeoutInSeconds>60</forkedProcessTimeoutInSeconds>

Review Comment:
   In the `jni-test` profile, `<excludes combine.self=\"override\"/>` clears 
*all* inherited/existing Surefire excludes, not just the `JavaExceptionJniTest` 
exclusion added earlier. If any other excludes are configured upstream (parent 
POM, pluginManagement, etc.), they’ll be unintentionally dropped when 
`-Pjni-test` is enabled. Consider a configuration approach that re-enables only 
this test (e.g., moving the exclusion into a non-`jni-test` profile, or using 
includes in `jni-test`) while preserving other excludes.



##########
cpp/core/jni/JniError.h:
##########
@@ -28,11 +28,17 @@
 #endif
 
 #ifndef JNI_METHOD_END
-#define JNI_METHOD_END(fallback_expr)                                          
  \
-  }                                                                            
  \
-  catch (std::exception & e) {                                                 
  \
-    env->ThrowNew(gluten::getJniErrorState()->glutenExceptionClass(), 
e.what()); \
-    return fallback_expr;                                                      
  \
+#define JNI_METHOD_END(fallback_expr)                                          
        \
+  }                                                                            
        \
+  catch (const gluten::JavaException& e) {                                     
        \
+    e.throwToJava(env);                                                        
        \
+    return fallback_expr;                                                      
        \
+  }                                                                            
        \
+  catch (std::exception & e) {                                                 
        \
+    if (!env->ExceptionCheck() && 
!gluten::JavaException::throwNestedToJava(env, e)) { \
+      env->ThrowNew(gluten::getJniErrorState()->glutenExceptionClass(), 
e.what());     \
+    }                                                                          
        \
+    return fallback_expr;                                                      
        \

Review Comment:
   `catch (std::exception & e)` should be `const std::exception&` since the 
handler doesn’t mutate `e`. Also, the macro still allows non-`std::exception` 
throws to cross an `extern \"C\"` JNI boundary (which can lead to 
`std::terminate`). Consider adding a `catch (...)` that sets a generic 
`GlutenException` only when no Java exception is pending, mirroring the 
existing guard behavior.



##########
cpp/core/tests/JavaExceptionAllocationTest.cc:
##########
@@ -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.
+ */
+
+#include <gtest/gtest.h>
+
+#include <cstdlib>
+#include <new>
+#include <utility>
+
+#include "jni/JavaException.h"
+#include "tests/utils/TestJniEnvironment.h"
+
+namespace {
+thread_local bool failNextAllocation = false;
+}
+
+// This executable isolates the replacement allocator from other core tests.
+void* operator new(std::size_t size) {
+  if (std::exchange(failNextAllocation, false)) {
+    throw std::bad_alloc();
+  }
+  if (auto* memory = std::malloc(size == 0 ? 1 : size)) {
+    return memory;
+  }
+  throw std::bad_alloc();
+}
+
+void operator delete(void* memory) noexcept {
+  std::free(memory);
+}
+
+void operator delete(void* memory, std::size_t) noexcept {
+  std::free(memory);
+}
+
+TEST(JavaExceptionAllocationTest, stateAllocationFailureRetainsOriginal) {
+  gluten::TestJniEnvironment jni;
+  jni.pending = &jni.original;
+  failNextAllocation = true;
+  try {
+    gluten::JavaException::check(jni.env());
+    failNextAllocation = false;
+    FAIL() << "Expected std::bad_alloc";
+  } catch (const std::bad_alloc&) {
+    EXPECT_FALSE(std::exchange(failNextAllocation, false));
+  } catch (...) {
+    failNextAllocation = false;
+    throw;
+  }
+  EXPECT_EQ(jni.pending, &jni.original);
+  EXPECT_EQ(jni.createdGlobalRefs, 0);
+  EXPECT_EQ(jni.deletedGlobalRefs, 0);
+  EXPECT_EQ(jni.deletedLocalRefs, 1);
+  EXPECT_EQ(jni.pushedFrames, 0);
+  EXPECT_EQ(jni.poppedFrames, 0);
+  EXPECT_EQ(jni.releasedStrings, 0);
+}
+
+TEST(JavaExceptionAllocationTest, diagnosticAllocationFailureRetainsOriginal) {
+  gluten::TestJniEnvironment jni;
+  auto functions = *jni.env()->functions;
+  functions.GetStringUTFChars = [](JNIEnv*, jstring, jboolean*) -> const char* 
{
+    // The throwable is already captured; fail the native diagnostic string, 
not NewGlobalRef.
+    failNextAllocation = true;
+    return "original Java exception";
+  };
+  jni.env()->functions = &functions;

Review Comment:
   This mutates `jni.env()->functions` to point at a stack-local copy of the 
function table. It’s safe within the current test scope, but it’s easy to 
accidentally extend usage beyond the variable’s lifetime in future edits. 
Prefer an RAII guard that restores the original `functions` pointer in all 
paths, or store the modified table in a fixture/member with a clear lifetime.



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