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

zhztheplayer pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gluten.git


The following commit(s) were added to refs/heads/main by this push:
     new 73dae76e19 [VL] Preserve Java exceptions through native iterators 
(#13561)
73dae76e19 is described below

commit 73dae76e191b10dffa1cf56cdba66a0b5b95cbfa
Author: Felipe Pessoto <[email protected]>
AuthorDate: Thu Nov 26 10:13:50 2026 -0800

    [VL] Preserve Java exceptions through native iterators (#13561)
---
 .../sql/execution/GlutenJniExceptionSuite.scala    | 209 ++++++++++++++++
 cpp/core/jni/JavaException.cc                      |  52 +++-
 cpp/core/jni/JavaException.h                       |  13 +
 cpp/core/jni/JniError.cc                           |  67 +++++
 cpp/core/jni/JniError.h                            |  42 ++--
 cpp/core/jni/JniWrapper.cc                         |   2 +-
 cpp/core/tests/utils/TestJniEnvironment.h          |  23 +-
 cpp/velox/CMakeLists.txt                           |   1 +
 cpp/velox/compute/VeloxBackend.cc                  |  11 +-
 cpp/velox/jni/VeloxInputIterator.cc                |  40 +++
 cpp/velox/jni/VeloxInputIterator.h                 |  27 ++
 cpp/velox/jni/VeloxJavaException.h                 |  50 ++++
 cpp/velox/tests/CMakeLists.txt                     |   1 +
 cpp/velox/tests/VeloxJavaExceptionTest.cc          | 277 +++++++++++++++++++++
 docs/developers/NewToGluten.md                     |  21 +-
 .../GlutenDeltaNativeConstraintSuite.scala         | 207 +++++++++++++++
 16 files changed, 1002 insertions(+), 41 deletions(-)

diff --git 
a/backends-velox/src/test/scala/org/apache/spark/sql/execution/GlutenJniExceptionSuite.scala
 
b/backends-velox/src/test/scala/org/apache/spark/sql/execution/GlutenJniExceptionSuite.scala
new file mode 100644
index 0000000000..82508523ea
--- /dev/null
+++ 
b/backends-velox/src/test/scala/org/apache/spark/sql/execution/GlutenJniExceptionSuite.scala
@@ -0,0 +1,209 @@
+/*
+ * 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
+
+import org.apache.gluten.backendsapi.BackendsApiManager
+import org.apache.gluten.config.GlutenConfig
+import org.apache.gluten.exception.GlutenException
+import org.apache.gluten.substrait.`type`.TypeBuilder
+import org.apache.gluten.substrait.SubstraitContext
+import org.apache.gluten.substrait.plan.PlanBuilder
+import org.apache.gluten.substrait.rel.RelBuilder
+import org.apache.gluten.vectorized.{ColumnarBatchInIterator, 
ColumnarBatchOutIterator, NativePlanEvaluator}
+
+import org.apache.spark.{QueryContext, SparkArithmeticException, SparkConf, 
SparkNumberFormatException, SparkThrowable}
+import org.apache.spark.sql.GlutenQueryTest
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.vectorized.ColumnarBatch
+import org.apache.spark.task.TaskResources
+
+import java.io.PrintWriter
+import java.util.{Collections, Iterator => JIterator}
+
+class GlutenJniExceptionSuite extends GlutenQueryTest with SharedSparkSession {
+  override protected def sparkConf: SparkConf = {
+    super.sparkConf
+      .set("spark.plugins", "org.apache.gluten.GlutenPlugin")
+      .set("spark.default.parallelism", "1")
+      .set("spark.memory.offHeap.enabled", "true")
+      .set("spark.memory.offHeap.size", "1024MB")
+      .set("spark.ui.enabled", "false")
+      // TaskResources.runUnsafe uses stage -1, which would match the default 
dump stage.
+      .set(GlutenConfig.BENCHMARK_TASK_STAGEID.key, "0")
+  }
+
+  private def withNativeIterator(input: JIterator[ColumnarBatch], lateSplit: 
Boolean = false)(
+      f: ColumnarBatchOutIterator => Unit): Unit = {
+    assume(BackendsApiManager.getBackendName == "velox")
+    withTempDir {
+      spillDir =>
+        TaskResources.runUnsafe {
+          val context = new SubstraitContext
+          val names = Collections.singletonList("value")
+          val read = RelBuilder.makeReadRelForInputIterator(
+            Collections.singletonList(TypeBuilder.makeI32(false)),
+            names,
+            context,
+            context.nextOperatorId("exception-test"))
+          val plan = PlanBuilder.makePlan(context, 
Collections.singletonList(read), names)
+          val backend = BackendsApiManager.getBackendName
+          val inputs = Array(new ColumnarBatchInIterator(backend, input))
+          val out = NativePlanEvaluator
+            .create(backend)
+            .createKernelWithBatchIterator(
+              plan.toProtobuf.toByteArray,
+              Array.empty[Array[Byte]],
+              if (lateSplit) Array.empty[ColumnarBatchInIterator] else inputs,
+              0,
+              spillDir.getCanonicalPath)
+          try {
+            if (lateSplit) {
+              out.addIteratorSplits(inputs)
+            }
+            out.noMoreSplits()
+            f(out)
+          } finally {
+            out.close()
+          }
+        }
+    }
+  }
+
+  private def failingInput(
+      original: Throwable,
+      failInHasNext: Boolean): JIterator[ColumnarBatch] = {
+    new JIterator[ColumnarBatch] {
+      override def hasNext: Boolean = {
+        if (failInHasNext) {
+          throw original
+        }
+        true
+      }
+
+      override def next(): ColumnarBatch = throw original
+    }
+  }
+
+  for (lateSplit <- Seq(false, true); failInHasNext <- Seq(true, false)) {
+    test(s"JNI preserves the Spark throwable (lateSplit=$lateSplit, 
hasNext=$failInHasNext)") {
+      val errors = Seq(
+        new SparkArithmeticException(
+          "CAST_OVERFLOW",
+          Map(
+            "value" -> "128",
+            "sourceType" -> "\"INT\"",
+            "targetType" -> "\"TINYINT\"",
+            "ansiConfig" -> "\"spark.sql.ansi.enabled\""),
+          Array.empty[QueryContext],
+          ""
+        ),
+        new SparkNumberFormatException(
+          "CAST_INVALID_INPUT",
+          Map(
+            "expression" -> "'invalid'",
+            "sourceType" -> "\"STRING\"",
+            "targetType" -> "\"INT\"",
+            "ansiConfig" -> "\"spark.sql.ansi.enabled\""),
+          Array.empty[QueryContext],
+          ""
+        )
+      )
+      errors.foreach {
+        original =>
+          val cause = new IllegalStateException("original cause")
+          val suppressed = new IllegalArgumentException("original suppressed 
exception")
+          original.initCause(cause)
+          original.addSuppressed(suppressed)
+          val stack = original.getStackTrace.toSeq
+          val parameters = original.getMessageParameters
+          val errorClass = original.getErrorClass
+          val sqlState = original.getSqlState
+          withNativeIterator(failingInput(original, failInHasNext), lateSplit) 
{
+            out =>
+              val actual = intercept[Exception] {
+                out.hasNext0()
+              }
+              assert(actual eq original)
+              assert(actual.getClass == original.getClass)
+              assert(actual.getCause eq cause)
+              assert(actual.getSuppressed.toSeq == Seq(suppressed))
+              assert(actual.getStackTrace.toSeq == stack)
+              actual match {
+                case sparkError: SparkThrowable =>
+                  assert(sparkError.getErrorClass == errorClass)
+                  assert(sparkError.getMessageParameters == parameters)
+                  assert(sparkError.getSqlState == sqlState)
+                case _ => fail("Original SparkThrowable was lost")
+              }
+          }
+      }
+    }
+  }
+
+  test("nested native iterators retain the actual Java cause") {
+    val original = new ArithmeticException("original arithmetic error")
+    val translated = new GlutenException(original)
+    Seq(original, translated).foreach {
+      inputError =>
+        withNativeIterator(failingInput(inputError, failInHasNext = true)) {
+          inner =>
+            withNativeIterator(inner) {
+              outer =>
+                val actual = intercept[GlutenException] {
+                  outer.hasNext()
+                }
+                assert(actual.getCause eq original)
+                if (inputError eq translated) {
+                  assert(actual eq translated)
+                }
+            }
+        }
+    }
+  }
+
+  test("JNI restores Errors as well as Exceptions") {
+    val original = new AssertionError("original error")
+    withNativeIterator(failingInput(original, failInHasNext = false)) {
+      out =>
+        val actual = intercept[AssertionError] {
+          out.next0()
+        }
+        assert(actual eq original)
+    }
+  }
+
+  test("a failed stack trace describer does not replace the original 
throwable") {
+    val original = new ArithmeticException("original exception") {
+      override def printStackTrace(writer: PrintWriter): Unit = {
+        throw new IllegalStateException("stack trace description failed")
+      }
+    }
+    withNativeIterator(failingInput(original, failInHasNext = true)) {
+      out =>
+        val actual = intercept[ArithmeticException] {
+          out.hasNext0()
+        }
+        assert(actual eq original)
+    }
+  }
+
+  test("normal end of input is unchanged") {
+    withNativeIterator(Collections.emptyList[ColumnarBatch]().iterator()) {
+      out => assert(!out.hasNext())
+    }
+  }
+}
diff --git a/cpp/core/jni/JavaException.cc b/cpp/core/jni/JavaException.cc
index 22070a1e3e..cc83e8a5b4 100644
--- a/cpp/core/jni/JavaException.cc
+++ b/cpp/core/jni/JavaException.cc
@@ -152,22 +152,50 @@ void JavaException::throwToJava(JNIEnv* env) const 
noexcept {
   }
 }
 
-bool JavaException::throwNestedToJava(JNIEnv* env, const std::exception& 
error) noexcept {
-  const auto* nested = dynamic_cast<const std::nested_exception*>(&error);
-  if (nested == nullptr || nested->nested_ptr() == nullptr) {
-    return false;
+namespace {
+std::optional<JavaExceptionCause> findCause(const std::exception_ptr& cause, 
ExceptionUnwrapper unwrap) noexcept {
+  if (!cause) {
+    return std::nullopt;
   }
   try {
-    std::rethrow_exception(nested->nested_ptr());
-  } catch (const JavaException& original) {
-    original.throwToJava(env);
-    return true;
-  } catch (const std::exception& cause) {
-    return throwNestedToJava(env, cause);
+    std::rethrow_exception(cause);
+  } catch (const std::exception& e) {
+    return findJavaExceptionCause(e, unwrap);
+  } catch (const std::nested_exception& e) {
+    return findCause(e.nested_ptr(), unwrap);
   } catch (...) {
-    // Not a Java exception. Leave the enclosing native error to the existing 
JNI fallback.
-    return false;
+    return std::nullopt;
+  }
+}
+} // namespace
+
+std::optional<JavaExceptionCause> findJavaExceptionCause(
+    const std::exception& error,
+    ExceptionUnwrapper unwrap) noexcept {
+  if (const auto* java = dynamic_cast<const JavaException*>(&error)) {
+    return JavaExceptionCause{*java, false};
+  }
+  const auto wrapped = unwrap ? unwrap(error) : nullptr;
+  if (auto cause = findCause(wrapped, unwrap)) {
+    cause->viaBackend = true;
+    return cause;
+  }
+  const auto* nested = dynamic_cast<const std::nested_exception*>(&error);
+  if (nested && nested->nested_ptr() != wrapped) {
+    return findCause(nested->nested_ptr(), unwrap);
+  }
+  return std::nullopt;
+}
+
+bool JavaException::throwNestedToJava(JNIEnv* env, const std::exception& 
error) noexcept {
+  const auto* nested = dynamic_cast<const std::nested_exception*>(&error);
+  if (nested) {
+    if (auto cause = findCause(nested->nested_ptr(), nullptr)) {
+      cause->exception.throwToJava(env);
+      return true;
+    }
   }
+  return false;
 }
 
 void JavaException::check(JNIEnv* env) {
diff --git a/cpp/core/jni/JavaException.h b/cpp/core/jni/JavaException.h
index e1048172b4..1f4dddc157 100644
--- a/cpp/core/jni/JavaException.h
+++ b/cpp/core/jni/JavaException.h
@@ -21,6 +21,7 @@
 
 #include <exception>
 #include <memory>
+#include <optional>
 
 namespace gluten {
 
@@ -59,4 +60,16 @@ class JavaException final : public std::exception {
   std::shared_ptr<State> state_;
 };
 
+using ExceptionUnwrapper = std::exception_ptr (*)(const std::exception&) 
noexcept;
+
+struct JavaExceptionCause {
+  JavaException exception;
+  // A failed JNI Throw uses the Java diagnostic only when a backend-specific 
cause was recovered.
+  bool viaBackend;
+};
+
+std::optional<JavaExceptionCause> findJavaExceptionCause(
+    const std::exception& error,
+    ExceptionUnwrapper unwrap) noexcept;
+
 } // namespace gluten
diff --git a/cpp/core/jni/JniError.cc b/cpp/core/jni/JniError.cc
index 6d580aa319..ac6e72df5e 100644
--- a/cpp/core/jni/JniError.cc
+++ b/cpp/core/jni/JniError.cc
@@ -16,6 +16,73 @@
  */
 #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;
+  const auto it = std::find(entries.begin(), entries.end(), unwrap_);
+  if (it == entries.end()) {
+    LOG(ERROR) << "Cannot unregister JNI exception unwrapper: no matching 
registration";
+    return;
+  }
+  entries.erase(it);
+}
+
+void handleJniException(JNIEnv* env, const std::exception& error) {
+  if (env->ExceptionCheck()) {
+    return;
+  }
+  const auto cause = findJavaExceptionCause(error, unwrapBackendException);
+  if (cause) {
+    cause->exception.throwToJava(env);
+  }
+  if (!env->ExceptionCheck()) {
+    const char* message = cause && cause->viaBackend ? cause->exception.what() 
: error.what();
+    if (env->ThrowNew(getJniErrorState()->glutenExceptionClass(), message) != 
JNI_OK) {
+      LOG(ERROR) << "Unable to throw GlutenException at JNI boundary";
+    }
+  }
+}
+} // namespace gluten
+
 void gluten::JniErrorState::ensureInitialized(JNIEnv* env) {
   std::lock_guard<std::mutex> lockGuard(mtx_);
   if (initialized_) {
diff --git a/cpp/core/jni/JniError.h b/cpp/core/jni/JniError.h
index 2e09e82f54..50140d8683 100644
--- a/cpp/core/jni/JniError.h
+++ b/cpp/core/jni/JniError.h
@@ -30,33 +30,31 @@
 #endif
 
 #ifndef JNI_METHOD_END
-#define JNI_METHOD_END(fallback_expr)                                          
                  \
-  }                                                                            
                  \
-  catch (const gluten::JavaException& e) {                                     
                  \
-    if (!env->ExceptionCheck()) {                                              
                  \
-      e.throwToJava(env);                                                      
                  \
-    }                                                                          
                  \
-    if (!env->ExceptionCheck() &&                                              
                  \
-        env->ThrowNew(gluten::getJniErrorState()->glutenExceptionClass(), 
e.what()) != JNI_OK) { \
-      LOG(ERROR) << "Unable to throw GlutenException at JNI boundary";         
                  \
-    }                                                                          
                  \
-    return fallback_expr;                                                      
                  \
-  }                                                                            
                  \
-  catch (const std::exception& e) {                                            
                  \
-    if (!env->ExceptionCheck()) {                                              
                  \
-      gluten::JavaException::throwNestedToJava(env, e);                        
                  \
-    }                                                                          
                  \
-    if (!env->ExceptionCheck() &&                                              
                  \
-        env->ThrowNew(gluten::getJniErrorState()->glutenExceptionClass(), 
e.what()) != JNI_OK) { \
-      LOG(ERROR) << "Unable to throw GlutenException at JNI boundary";         
                  \
-    }                                                                          
                  \
-    return fallback_expr;                                                      
                  \
+#define JNI_METHOD_END(fallback_expr)   \
+  }                                     \
+  catch (const std::exception& e) {     \
+    gluten::handleJniException(env, e); \
+    return fallback_expr;               \
   }
-// macro ended
 #endif
 
 namespace gluten {
 
+// Register for the lifetime of the backend library. Called under the registry 
lock, the
+// callback must only inspect its own wrapper and return its immediate cause 
(otherwise nullptr).
+class JniExceptionUnwrapperRegistration final {
+ public:
+  explicit JniExceptionUnwrapperRegistration(ExceptionUnwrapper unwrap);
+  ~JniExceptionUnwrapperRegistration();
+  JniExceptionUnwrapperRegistration(const JniExceptionUnwrapperRegistration&) 
= delete;
+  JniExceptionUnwrapperRegistration& operator=(const 
JniExceptionUnwrapperRegistration&) = delete;
+
+ private:
+  ExceptionUnwrapper unwrap_;
+};
+
+void handleJniException(JNIEnv* env, const std::exception& error);
+
 class JniErrorState {
  public:
   virtual ~JniErrorState() = default;
diff --git a/cpp/core/jni/JniWrapper.cc b/cpp/core/jni/JniWrapper.cc
index 88a411324f..1ea7c2873c 100644
--- a/cpp/core/jni/JniWrapper.cc
+++ b/cpp/core/jni/JniWrapper.cc
@@ -553,7 +553,7 @@ JNIEXPORT jboolean JNICALL 
Java_org_apache_gluten_vectorized_ColumnarBatchOutIte
     if (iter == nullptr) {
       inputIterators.push_back(nullptr);
     } else {
-      auto arrayIter = std::make_unique<JniColumnarBatchIterator>(env, iter, 
ctx, idx);
+      auto arrayIter = createJniInputIterator(env, iter, ctx, idx);
       auto resultIter = std::make_shared<ResultIterator>(std::move(arrayIter));
       inputIterators.push_back(std::move(resultIter));
     }
diff --git a/cpp/core/tests/utils/TestJniEnvironment.h 
b/cpp/core/tests/utils/TestJniEnvironment.h
index 483e1b5b19..5a67270454 100644
--- a/cpp/core/tests/utils/TestJniEnvironment.h
+++ b/cpp/core/tests/utils/TestJniEnvironment.h
@@ -66,25 +66,39 @@ class TestJniEnvironment {
         self.pending = &self.secondary;
         return nullptr;
       }
+      ++self.createdGlobalRefs;
+      if (object == &self.describer_) {
+        return object;
+      }
       auto ref = new _jthrowable();
       self.globalRefs.emplace(ref, static_cast<jthrowable>(object));
-      ++self.createdGlobalRefs;
       return ref;
     };
     functions_.DeleteGlobalRef = [](JNIEnv* env, jobject object) {
       auto& self = from(env);
-      self.globalRefs.erase(object);
-      delete static_cast<jthrowable>(object);
+      if (object != &self.describer_) {
+        self.globalRefs.erase(object);
+        delete static_cast<jthrowable>(object);
+      }
       ++self.deletedGlobalRefs;
       self.deletingEnv = env;
     };
     functions_.DeleteLocalRef = [](JNIEnv* env, jobject) { 
++from(env).deletedLocalRefs; };
     functions_.Throw = [](JNIEnv* env, jthrowable throwable) {
       auto& self = from(env);
+      if (self.failThrow) {
+        return JNI_ERR;
+      }
       auto global = self.globalRefs.find(throwable);
       self.pending = global == self.globalRefs.end() ? throwable : 
global->second;
       return JNI_OK;
     };
+    functions_.ThrowNew = [](JNIEnv* env, jclass, const char* message) {
+      auto& self = from(env);
+      self.fallbackMessage = message;
+      self.pending = &self.fallback;
+      return JNI_OK;
+    };
     functions_.PushLocalFrame = [](JNIEnv* env, jint) {
       auto& self = from(env);
       if (self.failLocalFrame) {
@@ -155,6 +169,8 @@ class TestJniEnvironment {
 
   _jthrowable original;
   _jthrowable secondary;
+  _jthrowable fallback;
+  std::string fallbackMessage;
   jthrowable pending{nullptr};
   std::unordered_map<jobject, jthrowable> globalRefs;
   std::vector<std::string> foundClassNames;
@@ -168,6 +184,7 @@ class TestJniEnvironment {
   int detaches{0};
   bool workerAttached{false};
   bool failGlobalRef{false};
+  bool failThrow{false};
   bool failDescription{false};
   bool failLocalFrame{false};
   JNIEnv* deletingEnv{nullptr};
diff --git a/cpp/velox/CMakeLists.txt b/cpp/velox/CMakeLists.txt
index e31e9d9b59..ba9c36a2af 100644
--- a/cpp/velox/CMakeLists.txt
+++ b/cpp/velox/CMakeLists.txt
@@ -170,6 +170,7 @@ set(VELOX_SRCS
     jni/JniFileSystem.cc
     jni/JniUdf.cc
     jni/JniHashTable.cc
+    jni/VeloxInputIterator.cc
     memory/BufferOutputStream.cc
     memory/VeloxColumnarBatch.cc
     memory/VeloxMemoryManager.cc
diff --git a/cpp/velox/compute/VeloxBackend.cc 
b/cpp/velox/compute/VeloxBackend.cc
index 53573918bd..4377d4b5c4 100644
--- a/cpp/velox/compute/VeloxBackend.cc
+++ b/cpp/velox/compute/VeloxBackend.cc
@@ -50,7 +50,10 @@
 #ifdef ENABLE_S3
 #include "filesystem/GlutenS3FileSystem.h"
 #endif
+#include "jni/JniError.h"
 #include "jni/JniFileSystem.h"
+#include "jni/VeloxInputIterator.h"
+#include "jni/VeloxJavaException.h"
 #include "memory/GlutenBufferedInputBuilder.h"
 #include "operators/functions/SparkExprToSubfieldFilterParser.h"
 #include "operators/plannodes/RowVectorStream.h"
@@ -127,6 +130,10 @@ void veloxThreadManagerReleaser(ThreadManager* 
threadManager) {
   delete threadManager;
 }
 
+void registerVeloxExceptionUnwrapper() {
+  static const JniExceptionUnwrapperRegistration 
registration(unwrapVeloxException);
+}
+
 bool hasCudaDevice() {
 #ifdef GLUTEN_ENABLE_GPU
   int count = 0;
@@ -160,10 +167,12 @@ void VeloxBackend::init(
 
   globalMemoryManager_ = 
std::make_unique<VeloxMemoryManager>(kVeloxBackendKind, std::move(listener), 
*backendConf_);
 
-  // Register factories.
+  // Register backend factories and JNI hooks.
   MemoryManager::registerFactory(kVeloxBackendKind, veloxMemoryManagerFactory, 
veloxMemoryManagerReleaser);
   ThreadManager::registerFactory(kVeloxBackendKind, veloxThreadManagerFactory, 
veloxThreadManagerReleaser);
   Runtime::registerFactory(kVeloxBackendKind, veloxRuntimeFactory, 
veloxRuntimeReleaser);
+  registerJniInputIteratorFactory(kVeloxBackendKind, 
createVeloxJniInputIterator);
+  registerVeloxExceptionUnwrapper();
 
   if (backendConf_->get<bool>(kDebugModeEnabled, false)) {
     LOG(INFO) << "VeloxBackend config:" << 
printConfig(backendConf_->rawConfigs());
diff --git a/cpp/velox/jni/VeloxInputIterator.cc 
b/cpp/velox/jni/VeloxInputIterator.cc
new file mode 100644
index 0000000000..383d70d96d
--- /dev/null
+++ b/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(); 
});
+  }
+};
+
+} // namespace
+
+std::unique_ptr<ColumnarBatchIterator>
+createVeloxJniInputIterator(JNIEnv* env, jobject iterator, Runtime* runtime, 
int32_t iteratorIndex) {
+  return std::make_unique<VeloxJniColumnarBatchIterator>(env, iterator, 
runtime, iteratorIndex);
+}
+
+} // namespace gluten
diff --git a/cpp/velox/jni/VeloxInputIterator.h 
b/cpp/velox/jni/VeloxInputIterator.h
new file mode 100644
index 0000000000..54ab24107c
--- /dev/null
+++ b/cpp/velox/jni/VeloxInputIterator.h
@@ -0,0 +1,27 @@
+/*
+ * 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/JniCommon.h"
+
+namespace gluten {
+
+std::unique_ptr<ColumnarBatchIterator>
+createVeloxJniInputIterator(JNIEnv* env, jobject iterator, Runtime* runtime, 
int32_t iteratorIndex);
+
+} // namespace gluten
diff --git a/cpp/velox/jni/VeloxJavaException.h 
b/cpp/velox/jni/VeloxJavaException.h
new file mode 100644
index 0000000000..70b8c0d419
--- /dev/null
+++ b/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));
+  }
+}
+
+inline std::exception_ptr unwrapVeloxException(const std::exception& error) 
noexcept {
+  const auto* veloxError = dynamic_cast<const 
facebook::velox::VeloxException*>(&error);
+  return veloxError ? veloxError->wrappedException() : nullptr;
+}
+
+} // namespace gluten
diff --git a/cpp/velox/tests/CMakeLists.txt b/cpp/velox/tests/CMakeLists.txt
index d1685a8b34..53fed1703e 100644
--- a/cpp/velox/tests/CMakeLists.txt
+++ b/cpp/velox/tests/CMakeLists.txt
@@ -157,6 +157,7 @@ add_velox_test(spark_functions_test SOURCES 
SparkFunctionTest.cc
                FunctionTest.cc IncrementMetricFunctionTest.cc)
 add_velox_test(runtime_test SOURCES RuntimeTest.cc)
 add_velox_test(velox_backend_test SOURCES VeloxBackendTest.cc)
+add_velox_test(velox_java_exception_test SOURCES VeloxJavaExceptionTest.cc)
 add_velox_test(velox_memory_test SOURCES MemoryManagerTest.cc)
 add_velox_test(buffer_outputstream_test SOURCES BufferOutputStreamTest.cc)
 add_velox_test(velox_whole_stage_dumper_test SOURCES
diff --git a/cpp/velox/tests/VeloxJavaExceptionTest.cc 
b/cpp/velox/tests/VeloxJavaExceptionTest.cc
new file mode 100644
index 0000000000..aa833ae2db
--- /dev/null
+++ b/cpp/velox/tests/VeloxJavaExceptionTest.cc
@@ -0,0 +1,277 @@
+/*
+ * 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 "compute/ResultIterator.h"
+#include "compute/VeloxBackend.h"
+#include "compute/WholeStageResultIterator.h"
+#include "config/GlutenConfig.h"
+#include "jni/JniError.h"
+#include "jni/VeloxJavaException.h"
+#include "tests/utils/TestJniEnvironment.h"
+#include "velox/exec/Driver.h"
+#include "velox/exec/tests/utils/TempDirectoryPath.h"
+#include "velox/vector/tests/utils/VectorTestBase.h"
+
+namespace gluten {
+namespace {
+
+using namespace facebook::velox;
+
+bool returnToJava(JNIEnv* env, const std::exception_ptr& error) {
+  JNI_METHOD_START
+  std::rethrow_exception(error);
+  JNI_METHOD_END(false)
+}
+
+class VeloxJavaExceptionTest : public ::testing::Test {
+ protected:
+  static inline TestJniEnvironment boundaryJni;
+
+  static void SetUpTestSuite() {
+    VeloxBackend::create(AllocationListener::noop(), {{kSessionTimezone, 
"UTC"}});
+    getJniErrorState()->ensureInitialized(boundaryJni.env());
+  }
+
+  static void TearDownTestSuite() {
+    getJniErrorState()->close();
+    EXPECT_EQ(boundaryJni.createdGlobalRefs, boundaryJni.deletedGlobalRefs);
+    VeloxBackend::get()->tearDown();
+  }
+};
+
+TEST_F(VeloxJavaExceptionTest, callbackIsWrappedBeforeReachingDriver) {
+  TestJniEnvironment jni;
+  try {
+    wrapJavaException([&]() { throw JavaException(jni.env(), &jni.original); 
});
+    FAIL() << "Expected VeloxException";
+  } catch (const VeloxException& error) {
+    EXPECT_EQ(error.exceptionType(), VeloxException::Type::kSystem);
+    ASSERT_NE(error.wrappedException(), nullptr);
+    EXPECT_FALSE(returnToJava(jni.env(), std::current_exception()));
+  }
+  EXPECT_EQ(jni.pending, &jni.original);
+  EXPECT_EQ(jni.deletedGlobalRefs, 1);
+}
+
+TEST_F(VeloxJavaExceptionTest, nestedNativeWrappersRetainOriginal) {
+  struct NativeContext {};
+  TestJniEnvironment jni;
+  {
+    auto error = std::make_exception_ptr(JavaException(jni.env(), 
&jni.original));
+    error = std::make_exception_ptr(VeloxUserError(error, "inner Velox 
wrapper", false));
+    try {
+      std::rethrow_exception(error);
+    } catch (...) {
+      try {
+        // std::throw_with_nested can wrap a type that isn't a std::exception.
+        std::throw_with_nested(NativeContext{});
+      } catch (...) {
+        error = std::current_exception();
+      }
+    }
+    error = std::make_exception_ptr(VeloxRuntimeError(error, "outer Velox 
wrapper", false));
+    EXPECT_FALSE(returnToJava(jni.env(), error));
+    EXPECT_EQ(jni.deletedGlobalRefs, 0);
+  }
+  EXPECT_EQ(jni.pending, &jni.original);
+  EXPECT_EQ(jni.deletedGlobalRefs, 1);
+}
+
+TEST_F(VeloxJavaExceptionTest, nativeExceptionsAreNotChanged) {
+  auto& jni = boundaryJni;
+  const auto original = std::make_exception_ptr(std::runtime_error("native 
error"));
+  try {
+    wrapJavaException([&]() { std::rethrow_exception(original); });
+    FAIL() << "Expected native exception";
+  } catch (const std::runtime_error&) {
+    EXPECT_EQ(std::current_exception(), original);
+    EXPECT_FALSE(returnToJava(jni.env(), std::current_exception()));
+    EXPECT_EQ(jni.pending, &jni.fallback);
+    EXPECT_EQ(jni.fallbackMessage, "native error");
+    jni.pending = nullptr;
+  }
+  for (const auto& cause : {original, std::make_exception_ptr(42), 
std::exception_ptr{}}) {
+    const VeloxUserError wrapped(cause, "native wrapper", false);
+    EXPECT_FALSE(returnToJava(jni.env(), std::make_exception_ptr(wrapped)));
+    EXPECT_EQ(jni.pending, &jni.fallback);
+    EXPECT_EQ(jni.fallbackMessage, wrapped.what());
+    jni.pending = nullptr;
+  }
+}
+
+TEST_F(VeloxJavaExceptionTest, javaCauseInStandardNestedVeloxException) {
+  TestJniEnvironment jni;
+  try {
+    throw JavaException(jni.env(), &jni.original);
+  } catch (...) {
+    try {
+      const auto native = 
std::make_exception_ptr(std::runtime_error("unrelated native cause"));
+      std::throw_with_nested(VeloxUserError(native, "two native wrapper 
mechanisms", false));
+    } catch (...) {
+      EXPECT_FALSE(returnToJava(jni.env(), std::current_exception()));
+    }
+  }
+  EXPECT_EQ(jni.pending, &jni.original);
+  EXPECT_EQ(jni.deletedGlobalRefs, 1);
+}
+
+TEST_F(VeloxJavaExceptionTest, 
sharedHandlerPreservesPendingAndFallsBackOnFailedRestore) {
+  auto& jni = boundaryJni;
+  const JavaException original(jni.env(), &jni.original);
+  const auto error =
+      
std::make_exception_ptr(VeloxRuntimeError(std::make_exception_ptr(original), 
"outer wrapper", false));
+
+  jni.pending = &jni.secondary;
+  EXPECT_FALSE(returnToJava(jni.env(), error));
+  EXPECT_EQ(jni.pending, &jni.secondary);
+
+  jni.pending = nullptr;
+  jni.failThrow = true;
+  EXPECT_FALSE(returnToJava(jni.env(), error));
+  EXPECT_EQ(jni.pending, &jni.fallback);
+  EXPECT_EQ(jni.fallbackMessage, original.what());
+  jni.pending = nullptr;
+  try {
+    throw original;
+  } catch (...) {
+    try {
+      std::throw_with_nested(std::runtime_error("standard wrapper"));
+    } catch (...) {
+      EXPECT_FALSE(returnToJava(jni.env(), std::current_exception()));
+      EXPECT_EQ(jni.pending, &jni.fallback);
+      EXPECT_EQ(jni.fallbackMessage, "standard wrapper");
+    }
+  }
+  jni.failThrow = false;
+  jni.pending = nullptr;
+}
+
+TEST_F(VeloxJavaExceptionTest, 
registrationIsScopedAndComposesWithOtherWrappers) {
+  struct BackendError : std::runtime_error {
+    explicit BackendError(std::exception_ptr cause) : 
std::runtime_error("other backend"), cause(std::move(cause)) {}
+    std::exception_ptr cause;
+  };
+  auto& jni = boundaryJni;
+  auto error = 
std::make_exception_ptr(BackendError(std::make_exception_ptr(VeloxRuntimeError(
+      std::make_exception_ptr(JavaException(jni.env(), &jni.original)), "inner 
Velox wrapper", false))));
+  try {
+    std::rethrow_exception(error);
+  } catch (...) {
+    try {
+      std::throw_with_nested(std::runtime_error("outer standard wrapper"));
+    } catch (...) {
+      error = std::current_exception();
+    }
+  }
+  {
+    static int matches;
+    matches = 0;
+    const JniExceptionUnwrapperRegistration registration([](const 
std::exception& e) noexcept -> std::exception_ptr {
+      if (auto* other = dynamic_cast<const BackendError*>(&e)) {
+        ++matches;
+        return other->cause;
+      }
+      return nullptr;
+    });
+    jni.pending = &jni.secondary;
+    EXPECT_FALSE(returnToJava(jni.env(), error));
+    EXPECT_EQ(jni.pending, &jni.secondary);
+    EXPECT_EQ(matches, 0);
+    jni.pending = nullptr;
+    EXPECT_FALSE(returnToJava(jni.env(), error));
+    EXPECT_EQ(jni.pending, &jni.original);
+    EXPECT_EQ(matches, 1);
+  }
+  jni.pending = nullptr;
+  EXPECT_FALSE(returnToJava(jni.env(), error));
+  EXPECT_EQ(jni.pending, &jni.fallback);
+  EXPECT_EQ(jni.fallbackMessage, "outer standard wrapper");
+  jni.pending = nullptr;
+}
+
+TEST_F(VeloxJavaExceptionTest, lazyOutputRestoresOriginalOnlyAtJniBoundary) {
+  auto* backend = VeloxBackend::get();
+  auto* memoryManager = backend->getGlobalMemoryManager();
+  auto* pool = memoryManager->getLeafMemoryPool().get();
+  auto spillDir = exec::test::TempDirectoryPath::create();
+
+  enum class Read { kNative, kJniHasNext, kJniNext, kJniNativeError };
+  for (const auto read : {Read::kNative, Read::kJniHasNext, Read::kJniNext, 
Read::kJniNativeError}) {
+    SCOPED_TRACE(static_cast<int>(read));
+    auto& jni = boundaryJni;
+    jni.pending = nullptr;
+    const auto refsBefore = jni.createdGlobalRefs - jni.deletedGlobalRefs;
+    const VeloxRuntimeError nativeError(
+        std::make_exception_ptr(std::runtime_error("native cause")), "native 
lazy load", false);
+    bool loaded = false;
+    bool loadedInDriver = false;
+    auto lazy = std::make_shared<LazyVector>(
+        pool, INTEGER(), 1, 
std::make_unique<test::SimpleVectorLoader>([&](RowSet) -> VectorPtr {
+          loaded = true;
+          loadedInDriver = exec::driverThreadContext() != nullptr;
+          if (read == Read::kJniNativeError) {
+            throw nativeError;
+          }
+          // This wrapper has no std::nested_exception link; only the Velox 
cause points to Java.
+          throw VeloxRuntimeError(
+              std::make_exception_ptr(JavaException(jni.env(), 
&jni.original)), "lazy Java callback", false);
+        }));
+    auto batch =
+        std::make_shared<RowVector>(pool, ROW({"value"}, {INTEGER()}), 
nullptr, 1, std::vector<VectorPtr>{lazy});
+    auto plan = std::make_shared<core::ValuesNode>("values", 
std::vector<RowVectorPtr>{batch});
+    {
+      ResultIterator iterator(std::make_unique<WholeStageResultIterator>(
+          memoryManager,
+          plan,
+          std::vector<core::PlanNodeId>{},
+          std::vector<std::shared_ptr<SplitInfo>>{},
+          std::vector<core::PlanNodeId>{},
+          backend->executor(),
+          backend->spillExecutor(),
+          VeloxConnectorIds{},
+          spillDir->getPath(),
+          backend->getBackendConf(),
+          SparkTaskInfo{}));
+      if (read == Read::kNative) {
+        EXPECT_THROW(iterator.next(), VeloxException);
+        EXPECT_EQ(jni.pending, nullptr);
+      } else {
+        auto readAtBoundary = [&](JNIEnv* env) {
+          JNI_METHOD_START
+          return read == Read::kJniHasNext ? iterator.hasNext() : 
iterator.next() != nullptr;
+          JNI_METHOD_END(false)
+        };
+        EXPECT_FALSE(readAtBoundary(jni.env()));
+        if (read == Read::kJniNativeError) {
+          EXPECT_EQ(jni.pending, &jni.fallback);
+          EXPECT_EQ(jni.fallbackMessage, nativeError.what());
+        } else {
+          EXPECT_EQ(jni.pending, &jni.original);
+        }
+      }
+    }
+    EXPECT_TRUE(loaded);
+    EXPECT_FALSE(loadedInDriver);
+    EXPECT_EQ(jni.createdGlobalRefs - jni.deletedGlobalRefs, refsBefore);
+    jni.pending = nullptr;
+  }
+}
+
+} // namespace
+} // namespace gluten
diff --git a/docs/developers/NewToGluten.md b/docs/developers/NewToGluten.md
index 79c7f2c8e0..19d7b36394 100644
--- a/docs/developers/NewToGluten.md
+++ b/docs/developers/NewToGluten.md
@@ -130,8 +130,17 @@ wrappers. Other native errors keep their existing 
`GlutenException` fallback.
 If carrier restoration leaves no pending Java exception, the boundary attempts
 that same fallback using the caught exception's diagnostic. A newer pending 
Java
 exception is left untouched; failure to throw the fallback is logged.
-Backend-specific callback and output-boundary propagation is separate from this
-core contract; it does not by itself protect the full Velox driver path.
+
+The Velox JNI input iterator uses `wrapJavaException` for both initial inputs
+and inputs added later through `addIteratorSplits`. This preserves the 
throwable
+before the driver, whose generic native-exception handler keeps only the 
message.
+Velox registers how to extract a `VeloxException`'s wrapped cause at backend
+initialization. The ordinary `JNI_METHOD_END` handler follows registered and
+standard nested causes without a runtime, including when lazy loading fails.
+It leaves an already-pending Java exception alone. Native callers still see the
+native exception. The runtime/system wrapper prevents TRY expressions from 
suppressing
+failed Java callbacks. Other native errors keep their existing handling; this
+mechanism does not classify or translate native cast failures.
 Preserving the throwable does not merge Java and C++ frames into a hybrid stack
 trace (see [#9642](https://github.com/apache/gluten/issues/9642)).
 
@@ -146,6 +155,14 @@ a missing library fails the tests rather than skipping 
them. The existing
 its Java 17 Maven step. No separate test artifact is needed, and the bridge is
 neither installed nor bundled in production jars.
 
+`GlutenDeltaNativeConstraintSuite` checks CHECK, NOT NULL, and replaceWhere 
violations
+through native writes, including partitioned writes. It requires the original 
Delta
+exception type and compares structured metadata with the JVM writer, including 
the
+replaceWhere invariant-violation cause, then verifies that a rejected write 
leaves
+the Delta version, active files, and rows unchanged.
+Successful writes are checked through Parquet footers so JVM fallback cannot 
make
+the native-path regression pass unnoticed.
+
 ### C++ code development
 
 This guide is for remote debugging by connecting to the remote Linux server 
using `SSH`.
diff --git 
a/gluten-ut/spark35/src-delta/test/scala/org/apache/spark/sql/execution/datasources/GlutenDeltaNativeConstraintSuite.scala
 
b/gluten-ut/spark35/src-delta/test/scala/org/apache/spark/sql/execution/datasources/GlutenDeltaNativeConstraintSuite.scala
new file mode 100644
index 0000000000..8f34327a3d
--- /dev/null
+++ 
b/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)
+  }
+
+  for (partitioned <- Seq(false, true); notNull <- Seq(false, true)) {
+    val constraint = if (notNull) "NOT NULL" else "CHECK"
+    test(s"native Delta $constraint preserves the exception and commits 
nothing, " +
+      s"partitioned=$partitioned") {
+      assume(BackendTestUtils.isVeloxBackendLoaded())
+      withTempDir {
+        dir =>
+          val path = dir.getCanonicalPath
+          val nullability = if (notNull) " NOT NULL" else ""
+          val partitions = if (partitioned) " PARTITIONED BY (part)" else ""
+          sql(
+            s"CREATE TABLE delta.`$path` (id BIGINT$nullability, part INT) 
USING delta$partitions")
+          if (!notNull) {
+            sql(s"ALTER TABLE delta.`$path` ADD CONSTRAINT positive_id CHECK 
(id > 0)")
+          }
+          append(path, Seq(Row(1L, 0), Row(2L, 1)))
+          assertNativeFiles(path)
+
+          val invalidId = if (notNull) null else Long.box(-1L)
+          val invalidRows = Seq(Row(3L, 0), Row(invalidId, 1))
+          val errorClass =
+            if (notNull) "DELTA_NOT_NULL_CONSTRAINT_VIOLATED"
+            else "DELTA_VIOLATE_CONSTRAINT_WITH_VALUES"
+          val actual = rejectedWrite(path, invalidRows, errorClass)
+          withSQLConf(nativeWriteKey -> "false") {
+            val expected = rejectedWrite(path, invalidRows, errorClass)
+            assertSameError(actual, expected)
+            if (notNull) {
+              assert(
+                actual.getSuppressed.toSeq.map(_.getClass) ==
+                  expected.getSuppressed.toSeq.map(_.getClass),
+                "A NOT NULL violation rebuilt from text suppresses the 
original write failure"
+              )
+            }
+          }
+      }
+    }
+  }
+
+  for (partitioned <- Seq(false, true)) {
+    test(s"native Delta replaceWhere preserves the exception and commits 
nothing, " +
+      s"partitioned=$partitioned") {
+      assume(BackendTestUtils.isVeloxBackendLoaded())
+      withSQLConf(DeltaSQLConf.REPLACEWHERE_DATACOLUMNS_ENABLED.key -> "true") 
{
+        withTempDir {
+          dir =>
+            val path = dir.getCanonicalPath
+            val partitions = if (partitioned) " PARTITIONED BY (part)" else ""
+            sql(s"CREATE TABLE delta.`$path` (id BIGINT, part INT) USING 
delta$partitions")
+            append(path, Seq(Row(1L, 0), Row(2L, 1)))
+            assertNativeFiles(path)
+
+            def rejectOverwrite(): DeltaAnalysisException = 
withUnchangedTable(path) {
+              val error = intercept[DeltaAnalysisException] {
+                input(Seq(Row(1L, 0), Row(4L, 1)))
+                  .write
+                  .format("delta")
+                  .mode("overwrite")
+                  .option("replaceWhere", "id < 3")
+                  .save(path)
+              }
+              assert(error.getErrorClass == "DELTA_REPLACE_WHERE_MISMATCH")
+              error
+            }
+
+            val actual = rejectOverwrite()
+            withSQLConf(nativeWriteKey -> "false") {
+              val expected = rejectOverwrite()
+              assertSameError(actual, expected)
+              (actual.getCause, expected.getCause) match {
+                case (
+                      actualCause: DeltaInvariantViolationException,
+                      expectedCause: DeltaInvariantViolationException) =>
+                  assertSameError(actualCause, expectedCause)
+                case _ => fail("Original Delta invariant violation cause was 
lost")
+              }
+            }
+        }
+      }
+    }
+  }
+}


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

Reply via email to