felipepessoto commented on code in PR #13561:
URL: https://github.com/apache/gluten/pull/13561#discussion_r4686399926


##########
cpp/velox/jni/VeloxJavaException.h:
##########
@@ -0,0 +1,50 @@
+/*
+ * 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 <utility>
+
+#include "jni/JavaException.h"
+#include "velox/common/base/VeloxException.h"
+
+namespace gluten {
+
+template <typename F>
+decltype(auto) wrapJavaException(F&& callback) {
+  try {
+    return std::forward<F>(callback)();
+  } catch (const JavaException& error) {
+    // Driver's std::exception catch keeps only what(); VeloxException keeps 
the exception_ptr.
+    // Use a runtime error so TRY expressions cannot suppress a failed Java 
callback.
+    // Standard nesting also lets other JNI boundaries recover the callback 
without knowing about Velox.
+    std::throw_with_nested(facebook::velox::VeloxException(
+        std::current_exception(),
+        error.what(),
+        facebook::velox::error_source::kErrorSourceRuntime,
+        false,
+        facebook::velox::VeloxException::Type::kSystem,
+        facebook::velox::VeloxRuntimeError::kDefaultName));

Review Comment:
   I’ve kept the base `VeloxException` here deliberately. In the [pinned Velox 
header](https://github.com/IBM/velox/blob/4770d62c6d8e302ee6372dfd4af1f2a53a5a081d/velox/common/base/VeloxException.h#L403),
 `VeloxRuntimeError` is `final`, so `std::throw_with_nested` can’t add a 
standard nested cause to it. The current construction keeps runtime/system 
semantics and exposes the original through both `wrappedException()` and 
`std::nested_exception`; switching types would drop the latter.



##########
gluten-ut/spark35/src-delta/test/scala/org/apache/spark/sql/execution/datasources/GlutenDeltaNativeConstraintSuite.scala:
##########
@@ -0,0 +1,207 @@
+/*
+ * 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.sql.execution.datasources
+
+import org.apache.gluten.config.GlutenConfig
+import org.apache.gluten.utils.BackendTestUtils
+
+import org.apache.spark.{SparkConf, SparkThrowable}
+import org.apache.spark.sql.{DataFrame, GlutenQueryTest, Row}
+import org.apache.spark.sql.delta.{DeltaAnalysisException, DeltaLog}
+import org.apache.spark.sql.delta.schema.DeltaInvariantViolationException
+import org.apache.spark.sql.delta.sources.DeltaSQLConf
+import org.apache.spark.sql.delta.util.DeltaFileOperations
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{IntegerType, LongType, StructType}
+
+import org.apache.parquet.hadoop.ParquetFileReader
+import org.apache.parquet.hadoop.util.HadoopInputFile
+
+class GlutenDeltaNativeConstraintSuite extends GlutenQueryTest with 
SharedSparkSession {
+
+  private val nativeWriteKey = 
"spark.gluten.sql.columnar.backend.velox.delta.enableNativeWrite"
+
+  override protected def sparkConf: SparkConf = {
+    super.sparkConf
+      .set("spark.plugins", "org.apache.gluten.GlutenPlugin")
+      .set("spark.shuffle.manager", 
"org.apache.spark.shuffle.sort.ColumnarShuffleManager")
+      .set("spark.default.parallelism", "1")
+      .set("spark.sql.shuffle.partitions", "1")
+      .set("spark.memory.offHeap.enabled", "true")
+      .set("spark.memory.offHeap.size", "1024MB")
+      .set("spark.ui.enabled", "false")
+      .set(GlutenConfig.GLUTEN_UI_ENABLED.key, "false")
+      .set("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")
+      .set("spark.sql.catalog.spark_catalog", 
"org.apache.spark.sql.delta.catalog.DeltaCatalog")
+      .set(nativeWriteKey, "true")
+      .set("spark.databricks.delta.snapshotPartitions", "1")
+      .set("spark.databricks.delta.optimizeWrite.enabled", "false")
+      .set("spark.sql.ansi.enabled", "false")
+      .set(GlutenConfig.GLUTEN_ANSI_FALLBACK_ENABLED.key, "false")
+      .set("spark.sql.adaptive.enabled", "false")
+      .set("spark.sql.maxConcurrentOutputFileWriters", "0")
+      // Exercise JNI even before the native writer supports materialized 
partition columns.
+      
.set("spark.databricks.delta.properties.defaults.writePartitionColumnsToParquet",
 "false")
+  }
+
+  private def input(rows: Seq[Row]): DataFrame = {
+    val schema = new StructType().add("id", LongType).add("part", IntegerType)
+    spark.createDataFrame(spark.sparkContext.parallelize(rows, 1), schema)
+  }
+
+  private def append(path: String, rows: Seq[Row]): Unit =
+    input(rows).write.format("delta").mode("append").save(path)
+
+  private def assertNativeFiles(path: String): Unit = {
+    val deltaLog = DeltaLog.forTable(spark, path)
+    val files = deltaLog.update().allFiles.collect()
+    assert(files.nonEmpty)
+    files.foreach {
+      file =>
+        val reader = ParquetFileReader.open(
+          HadoopInputFile.fromPath(
+            DeltaFileOperations.absolutePath(path, file.path),
+            deltaLog.newDeltaHadoopConf()))
+        try {
+          assert(
+            
reader.getFooter.getFileMetaData.getCreatedBy.startsWith("parquet-cpp-velox"),
+            s"${file.path} was not written by Velox")
+        } finally {
+          reader.close()
+        }
+    }
+  }
+
+  private def withUnchangedTable[T](path: String)(action: => T): T = {
+    val deltaLog = DeltaLog.forTable(spark, path)
+    val before = deltaLog.update()
+    val beforeFiles = before.allFiles.collect().toSet
+    val beforeRows = spark.read.format("delta").load(path).collect().toSeq
+
+    val result = action
+    val after = deltaLog.update()
+    assert(after.version == before.version, "A rejected write committed a new 
Delta version")
+    assert(after.allFiles.collect().toSet == beforeFiles)
+    checkAnswer(spark.read.format("delta").load(path), beforeRows)
+    result
+  }
+
+  private def rejectedWrite(
+      path: String,
+      rows: Seq[Row],
+      errorClass: String): DeltaInvariantViolationException = {
+    withUnchangedTable(path) {
+      val error = intercept[DeltaInvariantViolationException] {
+        append(path, rows)
+      }
+      assert(error.getErrorClass == errorClass)
+      error
+    }
+  }
+
+  private def assertSameError(
+      actual: Exception with SparkThrowable,
+      expected: Exception with SparkThrowable): Unit = {
+    assert(actual.getClass == expected.getClass)
+    assert(actual.getErrorClass == expected.getErrorClass)
+    assert(actual.getMessageParameters == expected.getMessageParameters)
+    assert(actual.getSqlState == expected.getSqlState)
+    assert(actual.getMessage == expected.getMessage)

Review Comment:
   The expected message isn’t a hard-coded string: the test repeats the same 
rejected write with native writes disabled, using the same Spark/Delta version 
and input. A wording change shared by both paths won’t fail the test. I’ve kept 
the equality check because a native-only change to the user-visible message is 
exactly the difference we want to catch, even if the structured fields still 
match.



##########
cpp/core/jni/JniError.cc:
##########
@@ -16,6 +16,68 @@
  */
 #include "JniError.h"
 
+#include <algorithm>
+#include <vector>
+
+namespace gluten {
+namespace {
+struct UnwrapperRegistry {
+  std::mutex mutex;
+  std::vector<ExceptionUnwrapper> unwrappers;
+};
+
+UnwrapperRegistry& unwrapperRegistry() {
+  static UnwrapperRegistry registry;
+  return registry;
+}
+
+std::exception_ptr unwrapBackendException(const std::exception& error) 
noexcept {
+  auto& registry = unwrapperRegistry();
+  // Unregistering a backend must wait until its callback has returned.
+  std::lock_guard<std::mutex> lock(registry.mutex);
+  for (auto unwrap : registry.unwrappers) {
+    if (auto cause = unwrap(error)) {
+      return cause;
+    }
+  }
+  return nullptr;
+}
+} // namespace
+
+JniExceptionUnwrapperRegistration::JniExceptionUnwrapperRegistration(ExceptionUnwrapper
 unwrap) : unwrap_(unwrap) {
+  GLUTEN_CHECK(unwrap != nullptr, "JNI exception unwrapper must not be null");
+  auto& registry = unwrapperRegistry();
+  std::lock_guard<std::mutex> lock(registry.mutex);
+  auto& entries = registry.unwrappers;
+  GLUTEN_CHECK(
+      std::find(entries.begin(), entries.end(), unwrap) == entries.end(), "JNI 
exception unwrapper already registered");
+  entries.push_back(unwrap);
+}
+
+JniExceptionUnwrapperRegistration::~JniExceptionUnwrapperRegistration() {
+  auto& registry = unwrapperRegistry();
+  std::lock_guard<std::mutex> lock(registry.mutex);
+  auto& entries = registry.unwrappers;
+  entries.erase(std::find(entries.begin(), entries.end(), unwrap_));

Review Comment:
   Fixed in 1f3230bd3. The destructor now checks for `end()`, logs the missing 
registration, and returns without erasing anything. I exercised that case in 
isolation with a second callback still registered: the diagnostic appeared 
once, and the other callback remained registered until its own destructor ran.



##########
cpp/velox/jni/VeloxInputIterator.cc:
##########
@@ -0,0 +1,40 @@
+/*
+ * 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/VeloxInputIterator.h"
+#include "jni/VeloxJavaException.h"
+
+namespace gluten {
+namespace {
+
+class VeloxJniColumnarBatchIterator final : public JniColumnarBatchIterator {
+ public:
+  using JniColumnarBatchIterator::JniColumnarBatchIterator;
+
+  std::shared_ptr<ColumnarBatch> next() override {
+    return wrapJavaException([this] { return JniColumnarBatchIterator::next(); 
});
+  }
+};

Review Comment:
   There isn’t a separate C++ `hasNext()` to override on 
`JniColumnarBatchIterator`. `ResultIterator::hasNext()` fetches through 
`iter_->next()`, and the [wrapped 
implementation](https://github.com/apache/gluten/blob/1f3230bd3bae6fa1772735227a76391db20177fc/cpp/core/jni/JniCommon.cc#L285-L309)
 calls both Java `hasNext()` and Java `next()`. The real-JVM tests throw from 
each callback on both initial and late inputs and check the throwable by 
identity. I’ve kept the single wrapper.



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