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 fb443acb3b [CORE] Preserve original Java exceptions across JNI 
(combined reference) (#13133)
fb443acb3b is described below

commit fb443acb3bd677d77396e2916f3f563a8e3e40ba
Author: Felipe Pessoto <[email protected]>
AuthorDate: Thu Nov 26 09:37:20 2026 -0800

    [CORE] Preserve original Java exceptions across JNI (combined reference) 
(#13133)
---
 cpp/velox/compute/WholeStageResultIterator.cc      |  36 +-
 cpp/velox/jni/VeloxJavaException.h                 |  66 ++++
 cpp/velox/memory/VeloxMemoryManager.cc             |  24 +-
 cpp/velox/operators/plannodes/CudfVectorStream.cc  |   5 +-
 cpp/velox/operators/plannodes/RowVectorStream.cc   |   5 +-
 cpp/velox/tests/CMakeLists.txt                     |   1 +
 cpp/velox/tests/VeloxJavaExceptionTest.cc          | 276 +++++++++++++++
 docs/developers/NewToGluten.md                     |  21 +-
 .../GlutenDeltaNativeConstraintSuite.scala         | 200 +++++++++++
 gluten-ut/test/pom.xml                             |  32 ++
 .../sql/execution/GlutenJniExceptionSuite.scala    | 381 +++++++++++++++++++++
 11 files changed, 1025 insertions(+), 22 deletions(-)

diff --git a/cpp/velox/compute/WholeStageResultIterator.cc 
b/cpp/velox/compute/WholeStageResultIterator.cc
index 0fae61ec00..8eae65d443 100644
--- a/cpp/velox/compute/WholeStageResultIterator.cc
+++ b/cpp/velox/compute/WholeStageResultIterator.cc
@@ -27,6 +27,7 @@
 #include "compute/delta/DeltaSplit.h"
 #include "compute/delta/DeltaSplitInfo.h"
 #include "config/VeloxConfig.h"
+#include "jni/VeloxJavaException.h"
 #include "operators/functions/IncrementMetricFunction.h"
 #include "utils/ConfigExtractor.h"
 #include "velox/connectors/hive/HiveConfig.h"
@@ -305,23 +306,28 @@ std::shared_ptr<velox::core::QueryCtx> 
WholeStageResultIterator::createNewVeloxQ
 }
 
 std::shared_ptr<ColumnarBatch> WholeStageResultIterator::next() {
-  while (true) {
-    if (!cursor_->moveNext()) {
-      return nullptr;
-    }
-    RowVectorPtr vector = cursor_->current();
-    GLUTEN_CHECK(vector != nullptr, "Cursor returned null vector.");
-    uint64_t numRows = vector->size();
-    if (numRows == 0) {
-      continue;
-    }
-    {
-      ScopedTimer timer(&loadLazyVectorTime_);
-      for (auto& child : vector->children()) {
-        child->loadedVector();
+  try {
+    while (true) {
+      if (!cursor_->moveNext()) {
+        return nullptr;
+      }
+      RowVectorPtr vector = cursor_->current();
+      GLUTEN_CHECK(vector != nullptr, "Cursor returned null vector.");
+      uint64_t numRows = vector->size();
+      if (numRows == 0) {
+        continue;
+      }
+      {
+        ScopedTimer timer(&loadLazyVectorTime_);
+        for (auto& child : vector->children()) {
+          child->loadedVector();
+        }
       }
+      return std::make_shared<VeloxColumnarBatch>(vector);
     }
-    return std::make_shared<VeloxColumnarBatch>(vector);
+  } catch (const std::exception&) {
+    rethrowJavaException(std::current_exception());
+    throw;
   }
 }
 
diff --git a/cpp/velox/jni/VeloxJavaException.h 
b/cpp/velox/jni/VeloxJavaException.h
new file mode 100644
index 0000000000..a7126d8cc2
--- /dev/null
+++ b/cpp/velox/jni/VeloxJavaException.h
@@ -0,0 +1,66 @@
+/*
+ * 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 core JNI recover callbacks outside 
WholeStageResultIterator.
+    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));
+  }
+}
+
+// Rethrow only a transported Java throwable. The caller must rethrow the 
original error otherwise.
+inline void rethrowJavaException(std::exception_ptr error) {
+  if (error == nullptr) {
+    return;
+  }
+  try {
+    std::rethrow_exception(error);
+  } catch (const JavaException&) {
+    throw;
+  } catch (const facebook::velox::VeloxException& e) {
+    rethrowJavaException(e.wrappedException());
+    if (const auto* nested = dynamic_cast<const std::nested_exception*>(&e)) {
+      rethrowJavaException(nested->nested_ptr());
+    }
+  } catch (const std::nested_exception& e) {
+    rethrowJavaException(e.nested_ptr());
+  } catch (...) {
+    // No transported Java throwable. The enclosing JNI boundary retains its 
native-error handling.
+  }
+}
+
+} // namespace gluten
diff --git a/cpp/velox/memory/VeloxMemoryManager.cc 
b/cpp/velox/memory/VeloxMemoryManager.cc
index ad46a6ce9b..329d8e0f77 100644
--- a/cpp/velox/memory/VeloxMemoryManager.cc
+++ b/cpp/velox/memory/VeloxMemoryManager.cc
@@ -28,6 +28,7 @@
 #include "velox/exec/MemoryReclaimer.h"
 
 #include "config/VeloxConfig.h"
+#include "jni/VeloxJavaException.h"
 #include "memory/ArrowMemoryPool.h"
 #include "utils/Exception.h"
 
@@ -51,6 +52,27 @@ std::unordered_map<std::string, std::string> 
getExtraArbitratorConfigs(
 }
 
 namespace {
+class JavaExceptionWrappingAllocationListener final : public 
AllocationListener {
+ public:
+  explicit 
JavaExceptionWrappingAllocationListener(std::unique_ptr<AllocationListener> 
delegate)
+      : delegate_(std::move(delegate)) {}
+
+  void allocationChanged(int64_t diff) override {
+    wrapJavaException([&]() { delegate_->allocationChanged(diff); });
+  }
+
+  int64_t currentBytes() override {
+    return delegate_->currentBytes();
+  }
+
+  int64_t peakBytes() override {
+    return delegate_->peakBytes();
+  }
+
+ private:
+  std::unique_ptr<AllocationListener> delegate_;
+};
+
 template <typename T>
 T getConfig(
     const std::unordered_map<std::string, std::string>& configs,
@@ -222,7 +244,7 @@ VeloxMemoryManager::VeloxMemoryManager(
     const std::string& kind,
     std::unique_ptr<AllocationListener> listener,
     const facebook::velox::config::ConfigBase& backendConf)
-    : MemoryManager(kind), listener_(std::move(listener)) {
+    : MemoryManager(kind), 
listener_(std::make_unique<JavaExceptionWrappingAllocationListener>(std::move(listener)))
 {
   auto reservationBlockSize =
       backendConf.get<uint64_t>(kMemoryReservationBlockSize, 
kMemoryReservationBlockSizeDefault);
   blockListener_ = std::make_unique<BlockAllocationListener>(listener_.get(), 
reservationBlockSize);
diff --git a/cpp/velox/operators/plannodes/CudfVectorStream.cc 
b/cpp/velox/operators/plannodes/CudfVectorStream.cc
index 2cec9b67b2..28fc775968 100644
--- a/cpp/velox/operators/plannodes/CudfVectorStream.cc
+++ b/cpp/velox/operators/plannodes/CudfVectorStream.cc
@@ -16,6 +16,7 @@
  */
 
 #include "CudfVectorStream.h"
+#include "jni/VeloxJavaException.h"
 #include "memory/VeloxColumnarBatch.h"
 #include "velox/exec/Driver.h"
 #include "velox/exec/Operator.h"
@@ -62,7 +63,7 @@ bool CudfVectorStreamBase::hasNext() {
     // 1. Task A spills task B;
     // 2. Task A tries to grow buffers created by task B, during which spill 
is requested on task A again.
     SuspendedSection ss(driverCtx_->driver);
-    hasNext = iterator_->hasNext();
+    hasNext = wrapJavaException([&]() { return iterator_->hasNext(); });
   }
   if (!hasNext) {
     finished_ = true;
@@ -79,7 +80,7 @@ std::shared_ptr<ColumnarBatch> 
CudfVectorStreamBase::nextInternal() {
     // We are leaving Velox task execution and are probably entering Spark 
code through JNI. Suspend the current
     // driver to make the current task open to spilling.
     SuspendedSection ss(driverCtx_->driver);
-    cb = iterator_->next();
+    cb = wrapJavaException([&]() { return iterator_->next(); });
   }
   return cb;
 }
diff --git a/cpp/velox/operators/plannodes/RowVectorStream.cc 
b/cpp/velox/operators/plannodes/RowVectorStream.cc
index 38872620cc..5a2e5dfc51 100644
--- a/cpp/velox/operators/plannodes/RowVectorStream.cc
+++ b/cpp/velox/operators/plannodes/RowVectorStream.cc
@@ -16,6 +16,7 @@
  */
 
 #include "RowVectorStream.h"
+#include "jni/VeloxJavaException.h"
 #include "memory/VeloxColumnarBatch.h"
 #include "velox/exec/Driver.h"
 #include "velox/exec/Operator.h"
@@ -70,7 +71,7 @@ bool RowVectorStream::hasNext() {
         "ExternalStreamDataSource::next() is not called "
         "from a driver thread");
     SuspendedSection ss(driverThreadCtx->driverCtx()->driver);
-    hasNext = iterator_->hasNext();
+    hasNext = wrapJavaException([&]() { return iterator_->hasNext(); });
   }
   if (!hasNext) {
     finished_ = true;
@@ -92,7 +93,7 @@ std::shared_ptr<ColumnarBatch> 
RowVectorStream::nextInternal() {
         "ExternalStreamDataSource::next() is not called "
         "from a driver thread");
     SuspendedSection ss(driverThreadCtx->driverCtx()->driver);
-    cb = iterator_->next();
+    cb = wrapJavaException([&]() { return iterator_->next(); });
   }
   return cb;
 }
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..f0ba9a4e52
--- /dev/null
+++ b/cpp/velox/tests/VeloxJavaExceptionTest.cc
@@ -0,0 +1,276 @@
+/*
+ * 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 <functional>
+
+#include "compute/VeloxBackend.h"
+#include "compute/WholeStageResultIterator.h"
+#include "config/GlutenConfig.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;
+
+class CallbackAllocationListener final : public AllocationListener {
+ public:
+  explicit CallbackAllocationListener(std::function<void(int64_t)> callback) : 
callback_(std::move(callback)) {}
+
+  void allocationChanged(int64_t diff) override {
+    callback_(diff);
+    currentBytes_ += diff;
+    peakBytes_ = std::max(currentBytes_, peakBytes_);
+  }
+
+  int64_t currentBytes() override {
+    return currentBytes_;
+  }
+
+  int64_t peakBytes() override {
+    return peakBytes_;
+  }
+
+ private:
+  std::function<void(int64_t)> callback_;
+  int64_t currentBytes_{0};
+  int64_t peakBytes_{0};
+};
+
+class VeloxJavaExceptionTest : public ::testing::Test {
+ protected:
+  static void SetUpTestSuite() {
+    VeloxBackend::create(AllocationListener::noop(), {{kSessionTimezone, 
"UTC"}});
+  }
+
+  static void TearDownTestSuite() {
+    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);
+    try {
+      rethrowJavaException(std::current_exception());
+      FAIL() << "Expected JavaException";
+    } catch (const JavaException& original) {
+      original.throwToJava(jni.env());
+    }
+  }
+  EXPECT_EQ(jni.pending, &jni.original);
+  EXPECT_EQ(jni.deletedGlobalRefs, 1);
+}
+
+TEST_F(VeloxJavaExceptionTest, nestedNativeWrappersRetainOriginal) {
+  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(std::runtime_error("nested native callback"));
+      } catch (...) {
+        error = std::current_exception();
+      }
+    }
+    error = std::make_exception_ptr(VeloxRuntimeError(error, "outer Velox 
wrapper", false));
+    try {
+      rethrowJavaException(error);
+      FAIL() << "Expected JavaException";
+    } catch (const JavaException& original) {
+      original.throwToJava(jni.env());
+    }
+    EXPECT_EQ(jni.deletedGlobalRefs, 0);
+  }
+  EXPECT_EQ(jni.pending, &jni.original);
+  EXPECT_EQ(jni.deletedGlobalRefs, 1);
+}
+
+TEST_F(VeloxJavaExceptionTest, nativeExceptionsAreNotChanged) {
+  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_NO_THROW(rethrowJavaException(std::current_exception()));
+  }
+  const auto wrapped = std::make_exception_ptr(VeloxUserError(original, 
"native wrapper", false));
+  EXPECT_NO_THROW(rethrowJavaException(wrapped));
+  EXPECT_NO_THROW(rethrowJavaException(std::make_exception_ptr(42)));
+  EXPECT_NO_THROW(rethrowJavaException(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 (...) {
+      try {
+        rethrowJavaException(std::current_exception());
+        FAIL() << "Expected JavaException";
+      } catch (const JavaException& original) {
+        original.throwToJava(jni.env());
+      }
+    }
+  }
+  EXPECT_EQ(jni.pending, &jni.original);
+  EXPECT_EQ(jni.deletedGlobalRefs, 1);
+}
+
+TEST_F(VeloxJavaExceptionTest, lazyOutputRestoresOriginalOutsideDriver) {
+  TestJniEnvironment jni;
+  auto* backend = VeloxBackend::get();
+  auto* memoryManager = backend->getGlobalMemoryManager();
+  auto* pool = memoryManager->getLeafMemoryPool().get();
+  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;
+          return wrapJavaException([&]() -> VectorPtr { throw 
JavaException(jni.env(), &jni.original); });
+        }));
+    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});
+    auto spillDir = exec::test::TempDirectoryPath::create();
+    WholeStageResultIterator iterator(
+        memoryManager,
+        plan,
+        {},
+        {},
+        {},
+        backend->executor(),
+        backend->spillExecutor(),
+        {},
+        spillDir->getPath(),
+        backend->getBackendConf(),
+        {});
+    try {
+      iterator.next();
+      FAIL() << "Expected JavaException";
+    } catch (const JavaException& error) {
+      error.throwToJava(jni.env());
+    }
+  }
+  EXPECT_TRUE(loaded);
+  EXPECT_FALSE(loadedInDriver);
+  EXPECT_EQ(jni.pending, &jni.original);
+  EXPECT_EQ(jni.createdGlobalRefs, jni.deletedGlobalRefs);
+}
+
+TEST_F(VeloxJavaExceptionTest, reservationsAreWrappedForBothNativeAllocators) {
+  for (const bool useArrow : {false, true}) {
+    SCOPED_TRACE(useArrow);
+    TestJniEnvironment jni;
+    auto listener = std::make_unique<CallbackAllocationListener>([&](int64_t 
diff) {
+      if (diff > 0) {
+        throw JavaException(jni.env(), &jni.original);
+      }
+    });
+    VeloxMemoryManager memoryManager(kVeloxBackendKind, std::move(listener), 
*VeloxBackend::get()->getBackendConf());
+    try {
+      if (useArrow) {
+        void* buffer = nullptr;
+        if (memoryManager.allocator()->allocate(64, &buffer)) {
+          memoryManager.allocator()->free(buffer, 64);
+        }
+      } else {
+        auto* pool = memoryManager.getLeafMemoryPool().get();
+        auto* buffer = pool->allocate(64);
+        pool->free(buffer, 64);
+      }
+      FAIL() << "Expected wrapped JavaException";
+    } catch (const VeloxException& error) {
+      EXPECT_EQ(error.exceptionType(), VeloxException::Type::kSystem);
+      EXPECT_TRUE(JavaException::throwNestedToJava(jni.env(), error));
+    }
+    EXPECT_EQ(jni.pending, &jni.original);
+    EXPECT_EQ(jni.createdGlobalRefs, 1);
+    EXPECT_EQ(jni.deletedGlobalRefs, 1);
+    EXPECT_EQ(memoryManager.getListener()->currentBytes(), 0);
+  }
+}
+
+TEST_F(VeloxJavaExceptionTest, 
unreservePreservesJavaExceptionAndDelegatedMetrics) {
+  TestJniEnvironment jni;
+  bool fail = false;
+  auto listener = std::make_unique<CallbackAllocationListener>([&](int64_t 
diff) {
+    if (fail && diff < 0) {
+      throw JavaException(jni.env(), &jni.original);
+    }
+  });
+  VeloxMemoryManager memoryManager(kVeloxBackendKind, std::move(listener), 
*VeloxBackend::get()->getBackendConf());
+  auto* wrapped = memoryManager.getListener();
+  wrapped->allocationChanged(64);
+  EXPECT_EQ(wrapped->currentBytes(), 64);
+  EXPECT_EQ(wrapped->peakBytes(), 64);
+  fail = true;
+  try {
+    wrapped->allocationChanged(-64);
+    FAIL() << "Expected wrapped JavaException";
+  } catch (const VeloxException& error) {
+    EXPECT_TRUE(JavaException::throwNestedToJava(jni.env(), error));
+  }
+  EXPECT_EQ(jni.pending, &jni.original);
+  EXPECT_EQ(jni.deletedGlobalRefs, 1);
+  fail = false;
+  wrapped->allocationChanged(-64);
+  EXPECT_EQ(wrapped->currentBytes(), 0);
+  EXPECT_EQ(wrapped->peakBytes(), 64);
+}
+
+TEST_F(VeloxJavaExceptionTest, nativeReservationErrorsAreUnchanged) {
+  const auto original = std::make_exception_ptr(std::runtime_error("native 
reservation failure"));
+  auto listener = std::make_unique<CallbackAllocationListener>([&](int64_t 
diff) {
+    if (diff > 0) {
+      std::rethrow_exception(original);
+    }
+  });
+  VeloxMemoryManager memoryManager(kVeloxBackendKind, std::move(listener), 
*VeloxBackend::get()->getBackendConf());
+  try {
+    auto* pool = memoryManager.getLeafMemoryPool().get();
+    auto* buffer = pool->allocate(64);
+    pool->free(buffer, 64);
+    FAIL() << "Expected native reservation failure";
+  } catch (const std::runtime_error&) {
+    EXPECT_EQ(std::current_exception(), original);
+  }
+}
+
+} // namespace
+} // namespace gluten
diff --git a/docs/developers/NewToGluten.md b/docs/developers/NewToGluten.md
index 79c7f2c8e0..4030658733 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.
+
+Velox input-stream and memory-reservation callbacks use `wrapJavaException` 
before
+returning to the driver, whose generic native-exception handler otherwise keeps
+only the message.
+At the output boundary, including lazy-vector loading, `rethrowJavaException`
+recovers the carrier through Velox and standard nested exception wrappers. The
+runtime/system wrapper prevents TRY expressions from suppressing failed Java
+callbacks. Standard nesting also preserves allocation callbacks returning 
directly
+through core JNI without introducing a backend dependency there. 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..adf74cddb8
--- /dev/null
+++ 
b/gluten-ut/spark35/src-delta/test/scala/org/apache/spark/sql/execution/datasources/GlutenDeltaNativeConstraintSuite.scala
@@ -0,0 +1,200 @@
+/*
+ * 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)
+          }
+      }
+    }
+  }
+
+  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")
+              }
+            }
+        }
+      }
+    }
+  }
+}
diff --git a/gluten-ut/test/pom.xml b/gluten-ut/test/pom.xml
index d470b53ad4..409760ca6e 100644
--- a/gluten-ut/test/pom.xml
+++ b/gluten-ut/test/pom.xml
@@ -162,6 +162,38 @@
           <scope>test</scope>
         </dependency>
       </dependencies>
+      <build>
+        <plugins>
+          <plugin>
+            <groupId>org.codehaus.mojo</groupId>
+            <artifactId>build-helper-maven-plugin</artifactId>
+            <executions>
+              <execution>
+                <id>add-velox-test-sources</id>
+                <goals>
+                  <goal>add-test-source</goal>
+                </goals>
+                <phase>generate-test-sources</phase>
+                <configuration>
+                  <sources>
+                    <source>${project.basedir}/src-velox/test/scala</source>
+                  </sources>
+                </configuration>
+              </execution>
+            </executions>
+          </plugin>
+          <plugin>
+            <groupId>org.scalastyle</groupId>
+            <artifactId>scalastyle-maven-plugin</artifactId>
+            <configuration>
+              <testSourceDirectories>
+                
<testSourceDirectory>${project.basedir}/src/test/scala</testSourceDirectory>
+                
<testSourceDirectory>${project.basedir}/src-velox/test/scala</testSourceDirectory>
+              </testSourceDirectories>
+            </configuration>
+          </plugin>
+        </plugins>
+      </build>
     </profile>
     <profile>
       <id>backends-bolt</id>
diff --git 
a/gluten-ut/test/src-velox/test/scala/org/apache/spark/sql/execution/GlutenJniExceptionSuite.scala
 
b/gluten-ut/test/src-velox/test/scala/org/apache/spark/sql/execution/GlutenJniExceptionSuite.scala
new file mode 100644
index 0000000000..d5349c30b4
--- /dev/null
+++ 
b/gluten-ut/test/src-velox/test/scala/org/apache/spark/sql/execution/GlutenJniExceptionSuite.scala
@@ -0,0 +1,381 @@
+/*
+ * 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.memory.{NativeMemoryManager, 
NativeMemoryManagerJniWrapper}
+import org.apache.gluten.memory.listener.ReservationListener
+import org.apache.gluten.memory.memtarget.Spiller
+import org.apache.gluten.runtime.{Runtime, RuntimeJniWrapper, Runtimes}
+import org.apache.gluten.substrait.`type`.{TypeBuilder, TypeNode}
+import org.apache.gluten.substrait.SubstraitContext
+import org.apache.gluten.substrait.expression.{ExpressionBuilder, 
ExpressionNode}
+import org.apache.gluten.substrait.plan.PlanBuilder
+import org.apache.gluten.substrait.rel.RelBuilder
+import org.apache.gluten.threads.NativeThreadManager
+import org.apache.gluten.utils.{BackendTestUtils, ConfigUtil}
+import org.apache.gluten.vectorized.{ColumnarBatchInIterator, 
ColumnarBatchOutIterator, NativePlanEvaluator, PlanEvaluatorJniWrapper}
+
+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, ColumnVector}
+import org.apache.spark.task.TaskResources
+
+import java.io.PrintWriter
+import java.util.{Collections, Iterator => JIterator}
+
+import scala.collection.JavaConverters._
+
+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])(
+      f: ColumnarBatchOutIterator => Unit): Unit = {
+    assume(BackendTestUtils.isVeloxBackendLoaded())
+    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 out = NativePlanEvaluator
+            .create(backend)
+            .createKernelWithBatchIterator(
+              plan.toProtobuf.toByteArray,
+              Array.empty[Array[Byte]],
+              Array(new ColumnarBatchInIterator(backend, input)),
+              0,
+              spillDir.getCanonicalPath)
+          try {
+            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
+    }
+  }
+
+  private def withReservationRuntime(listener: ReservationListener)(f: Runtime 
=> Unit): Unit = {
+    TaskResources.runUnsafe {
+      val backend = BackendsApiManager.getBackendName
+      val threadOwner = Runtimes.contextInstance(backend, 
"jni-reservation-test")
+      val conf = ConfigUtil.serialize(
+        Map(
+          "spark.sql.session.timeZone" -> "UTC",
+          "spark.gluten.memory.backtrace.allocation" -> "false").asJava)
+      val memoryHandle = NativeMemoryManagerJniWrapper.create(backend, 
listener, conf)
+      try {
+        val runtimeHandle = RuntimeJniWrapper.createRuntime(
+          backend,
+          memoryHandle,
+          threadOwner.threadManager().getHandle(),
+          conf)
+        try {
+          val nativeMemory = new NativeMemoryManager {
+            override def addSpiller(spiller: Spiller): Unit =
+              throw new UnsupportedOperationException("This test does not 
install spillers")
+            override def hold(): Unit = 
NativeMemoryManagerJniWrapper.hold(memoryHandle)
+            override def getHandle(): Long = memoryHandle
+            override def release(): Unit = 
NativeMemoryManagerJniWrapper.release(memoryHandle)
+          }
+          f(new Runtime {
+            override def memoryManager(): NativeMemoryManager = nativeMemory
+            override def threadManager(): NativeThreadManager = 
threadOwner.threadManager()
+            override def getHandle(): Long = runtimeHandle
+          })
+        } finally {
+          RuntimeJniWrapper.releaseRuntime(runtimeHandle)
+        }
+      } finally {
+        NativeMemoryManagerJniWrapper.release(memoryHandle)
+      }
+    }
+  }
+
+  private def withNativeCount(runtime: Runtime)(f: ColumnarBatchOutIterator => 
Unit): Unit = {
+    withTempDir {
+      spillDir =>
+        val context = new SubstraitContext
+        val read = RelBuilder.makeReadRelForInputIterator(
+          Collections.emptyList[TypeNode](),
+          Collections.emptyList[String](),
+          context,
+          context.nextOperatorId("reservation-input"))
+        val count = ExpressionBuilder.makeAggregateFunction(
+          context.registerFunction("count"),
+          Collections.emptyList[ExpressionNode](),
+          "COMPLETE",
+          TypeBuilder.makeI64(false))
+        val aggregate = RelBuilder.makeAggregateRel(
+          read,
+          Collections.emptyList[ExpressionNode](),
+          Collections.singletonList(count),
+          Collections.singletonList[ExpressionNode](null),
+          null,
+          context,
+          context.nextOperatorId("reservation-aggregate")
+        )
+        val plan = PlanBuilder.makePlan(
+          context,
+          Collections.singletonList(aggregate),
+          Collections.singletonList("count"))
+        val input = new ColumnarBatch(Array.empty[ColumnVector], 1)
+        val handle = PlanEvaluatorJniWrapper
+          .create(runtime)
+          .nativeCreateKernelWithIterator(
+            plan.toProtobuf.toByteArray,
+            Array.empty[Array[Byte]],
+            Array(new ColumnarBatchInIterator(
+              BackendsApiManager.getBackendName,
+              Collections.singletonList(input).iterator())),
+            0,
+            0,
+            0L,
+            false,
+            spillDir.getCanonicalPath
+          )
+        val out = new ColumnarBatchOutIterator(runtime, handle)
+        try {
+          out.noMoreSplits()
+          f(out)
+        } finally {
+          out.close()
+          input.close()
+        }
+    }
+  }
+
+  private class FailingReservationListener(val original: RuntimeException)
+    extends ReservationListener {
+    var failReserve = false
+    var failUnreserve = false
+    var failures = 0
+    private var used = 0L
+
+    override def reserve(size: Long): Long = {
+      if (failReserve) {
+        failures += 1
+        throw original
+      }
+      used += size
+      size
+    }
+
+    override def unreserve(size: Long): Long = {
+      used -= size
+      if (failUnreserve) {
+        failures += 1
+        throw original
+      }
+      size
+    }
+
+    override def getUsedBytes: Long = used
+  }
+
+  for (failInHasNext <- Seq(true, false)) {
+    test(s"Java throwable identity and Spark metadata survive JNI 
(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)) {
+            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())
+    }
+  }
+
+  test("native operator reservations preserve the actual Java throwable") {
+    val cause = new ArithmeticException("reservation cause")
+    val original = new IllegalStateException("reservation failure", cause)
+    val listener = new FailingReservationListener(original)
+    withReservationRuntime(listener) {
+      runtime =>
+        withNativeCount(runtime) {
+          out =>
+            listener.failReserve = true
+            try {
+              val actual = intercept[IllegalStateException] {
+                out.hasNext0()
+              }
+              assert(listener.failures > 0)
+              assert(actual eq original)
+              assert(actual.getCause eq cause)
+            } finally {
+              listener.failReserve = false
+            }
+        }
+    }
+  }
+
+  test("direct JNI unreserve preserves the actual Java throwable") {
+    val original = new IllegalStateException("unreserve failure")
+    val listener = new FailingReservationListener(original)
+    withReservationRuntime(listener) {
+      runtime =>
+        withNativeCount(runtime) {
+          out =>
+            assert(out.hasNext0())
+            val batch = out.next0()
+            batch.close()
+            assert(!out.hasNext0())
+        }
+        assert(listener.getUsedBytes > 0)
+        listener.failUnreserve = true
+        try {
+          val actual = intercept[IllegalStateException] {
+            
NativeMemoryManagerJniWrapper.shrink(runtime.memoryManager().getHandle(), 0)
+          }
+          assert(listener.failures > 0)
+          assert(actual eq original)
+        } finally {
+          listener.failUnreserve = false
+        }
+    }
+  }
+}


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

Reply via email to