Copilot commented on code in PR #13561: URL: https://github.com/apache/gluten/pull/13561#discussion_r4685757434
########## cpp/velox/jni/VeloxInputIterator.cc: ########## @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "jni/VeloxInputIterator.h" +#include "jni/VeloxJavaException.h" + +namespace gluten { +namespace { + +class VeloxJniColumnarBatchIterator final : public JniColumnarBatchIterator { + public: + using JniColumnarBatchIterator::JniColumnarBatchIterator; + + std::shared_ptr<ColumnarBatch> next() override { + return wrapJavaException([this] { return JniColumnarBatchIterator::next(); }); + } +}; Review Comment: Only `next()` is wrapped with `wrapJavaException`, but iterator reads also commonly call `hasNext()` (and the PR description explicitly mentions preserving failures from `nativeHasNext`). If `JniColumnarBatchIterator::hasNext()` can throw `JavaException`, that path will still reach the Velox driver unwrapped and lose the original throwable. Wrap `hasNext()` (and any other iterator entrypoints used by the driver) similarly so both `hasNext` and `next` preserve the Java throwable. ########## cpp/core/jni/JniError.cc: ########## @@ -16,6 +16,68 @@ */ #include "JniError.h" +#include <algorithm> +#include <vector> + +namespace gluten { +namespace { +struct UnwrapperRegistry { + std::mutex mutex; + std::vector<ExceptionUnwrapper> unwrappers; +}; + +UnwrapperRegistry& unwrapperRegistry() { + static UnwrapperRegistry registry; + return registry; +} + +std::exception_ptr unwrapBackendException(const std::exception& error) noexcept { + auto& registry = unwrapperRegistry(); + // Unregistering a backend must wait until its callback has returned. + std::lock_guard<std::mutex> lock(registry.mutex); + for (auto unwrap : registry.unwrappers) { + if (auto cause = unwrap(error)) { + return cause; + } + } + return nullptr; +} +} // namespace + +JniExceptionUnwrapperRegistration::JniExceptionUnwrapperRegistration(ExceptionUnwrapper unwrap) : unwrap_(unwrap) { + GLUTEN_CHECK(unwrap != nullptr, "JNI exception unwrapper must not be null"); + auto& registry = unwrapperRegistry(); + std::lock_guard<std::mutex> lock(registry.mutex); + auto& entries = registry.unwrappers; + GLUTEN_CHECK( + std::find(entries.begin(), entries.end(), unwrap) == entries.end(), "JNI exception unwrapper already registered"); + entries.push_back(unwrap); +} + +JniExceptionUnwrapperRegistration::~JniExceptionUnwrapperRegistration() { + auto& registry = unwrapperRegistry(); + std::lock_guard<std::mutex> lock(registry.mutex); + auto& entries = registry.unwrappers; + entries.erase(std::find(entries.begin(), entries.end(), unwrap_)); Review Comment: `entries.erase(std::find(...))` is undefined behavior if `unwrap_` isn’t found (e.g., if destructor runs unexpectedly or double-unregister occurs). Make this robust by checking the iterator against `entries.end()` and either no-op or assert with a clear error if it’s missing. ########## cpp/velox/jni/VeloxJavaException.h: ########## @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include <utility> + +#include "jni/JavaException.h" +#include "velox/common/base/VeloxException.h" + +namespace gluten { + +template <typename F> +decltype(auto) wrapJavaException(F&& callback) { + try { + return std::forward<F>(callback)(); + } catch (const JavaException& error) { + // Driver's std::exception catch keeps only what(); VeloxException keeps the exception_ptr. + // Use a runtime error so TRY expressions cannot suppress a failed Java callback. + // Standard nesting also lets other JNI boundaries recover the callback without knowing about Velox. + std::throw_with_nested(facebook::velox::VeloxException( + std::current_exception(), + error.what(), + facebook::velox::error_source::kErrorSourceRuntime, + false, + facebook::velox::VeloxException::Type::kSystem, + facebook::velox::VeloxRuntimeError::kDefaultName)); Review Comment: Constructing `facebook::velox::VeloxException` directly with a long parameter list (including a runtime-error name) makes the intent easy to misread and tightly couples this code to Velox constructor details. Prefer throwing the most specific Velox exception type/helper that expresses the intended semantics (runtime/system) so future Velox API changes are less likely to break this wrapper and the call site remains self-describing. ########## gluten-ut/spark35/src-delta/test/scala/org/apache/spark/sql/execution/datasources/GlutenDeltaNativeConstraintSuite.scala: ########## @@ -0,0 +1,207 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.spark.sql.execution.datasources + +import org.apache.gluten.config.GlutenConfig +import org.apache.gluten.utils.BackendTestUtils + +import org.apache.spark.{SparkConf, SparkThrowable} +import org.apache.spark.sql.{DataFrame, GlutenQueryTest, Row} +import org.apache.spark.sql.delta.{DeltaAnalysisException, DeltaLog} +import org.apache.spark.sql.delta.schema.DeltaInvariantViolationException +import org.apache.spark.sql.delta.sources.DeltaSQLConf +import org.apache.spark.sql.delta.util.DeltaFileOperations +import org.apache.spark.sql.test.SharedSparkSession +import org.apache.spark.sql.types.{IntegerType, LongType, StructType} + +import org.apache.parquet.hadoop.ParquetFileReader +import org.apache.parquet.hadoop.util.HadoopInputFile + +class GlutenDeltaNativeConstraintSuite extends GlutenQueryTest with SharedSparkSession { + + private val nativeWriteKey = "spark.gluten.sql.columnar.backend.velox.delta.enableNativeWrite" + + override protected def sparkConf: SparkConf = { + super.sparkConf + .set("spark.plugins", "org.apache.gluten.GlutenPlugin") + .set("spark.shuffle.manager", "org.apache.spark.shuffle.sort.ColumnarShuffleManager") + .set("spark.default.parallelism", "1") + .set("spark.sql.shuffle.partitions", "1") + .set("spark.memory.offHeap.enabled", "true") + .set("spark.memory.offHeap.size", "1024MB") + .set("spark.ui.enabled", "false") + .set(GlutenConfig.GLUTEN_UI_ENABLED.key, "false") + .set("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") + .set("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") + .set(nativeWriteKey, "true") + .set("spark.databricks.delta.snapshotPartitions", "1") + .set("spark.databricks.delta.optimizeWrite.enabled", "false") + .set("spark.sql.ansi.enabled", "false") + .set(GlutenConfig.GLUTEN_ANSI_FALLBACK_ENABLED.key, "false") + .set("spark.sql.adaptive.enabled", "false") + .set("spark.sql.maxConcurrentOutputFileWriters", "0") + // Exercise JNI even before the native writer supports materialized partition columns. + .set("spark.databricks.delta.properties.defaults.writePartitionColumnsToParquet", "false") + } + + private def input(rows: Seq[Row]): DataFrame = { + val schema = new StructType().add("id", LongType).add("part", IntegerType) + spark.createDataFrame(spark.sparkContext.parallelize(rows, 1), schema) + } + + private def append(path: String, rows: Seq[Row]): Unit = + input(rows).write.format("delta").mode("append").save(path) + + private def assertNativeFiles(path: String): Unit = { + val deltaLog = DeltaLog.forTable(spark, path) + val files = deltaLog.update().allFiles.collect() + assert(files.nonEmpty) + files.foreach { + file => + val reader = ParquetFileReader.open( + HadoopInputFile.fromPath( + DeltaFileOperations.absolutePath(path, file.path), + deltaLog.newDeltaHadoopConf())) + try { + assert( + reader.getFooter.getFileMetaData.getCreatedBy.startsWith("parquet-cpp-velox"), + s"${file.path} was not written by Velox") + } finally { + reader.close() + } + } + } + + private def withUnchangedTable[T](path: String)(action: => T): T = { + val deltaLog = DeltaLog.forTable(spark, path) + val before = deltaLog.update() + val beforeFiles = before.allFiles.collect().toSet + val beforeRows = spark.read.format("delta").load(path).collect().toSeq + + val result = action + val after = deltaLog.update() + assert(after.version == before.version, "A rejected write committed a new Delta version") + assert(after.allFiles.collect().toSet == beforeFiles) + checkAnswer(spark.read.format("delta").load(path), beforeRows) + result + } + + private def rejectedWrite( + path: String, + rows: Seq[Row], + errorClass: String): DeltaInvariantViolationException = { + withUnchangedTable(path) { + val error = intercept[DeltaInvariantViolationException] { + append(path, rows) + } + assert(error.getErrorClass == errorClass) + error + } + } + + private def assertSameError( + actual: Exception with SparkThrowable, + expected: Exception with SparkThrowable): Unit = { + assert(actual.getClass == expected.getClass) + assert(actual.getErrorClass == expected.getErrorClass) + assert(actual.getMessageParameters == expected.getMessageParameters) + assert(actual.getSqlState == expected.getSqlState) + assert(actual.getMessage == expected.getMessage) Review Comment: Asserting full `getMessage` equality in addition to `errorClass`, `messageParameters`, and `sqlState` is brittle for Spark/Delta errors (messages may vary across versions or include minor formatting differences) while not adding much signal beyond the structured fields already compared. Consider dropping the `getMessage` comparison (or restricting it to a minimal stable invariant) to reduce flaky failures across Spark/Delta upgrades. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
