Repository navigation
[CORE] Preserve Java throwables at the JNI boundary - #13560
zhztheplayer merged 12 commits into
Conversation
e7bf0b6 to
8aff74c
Compare
Split layer 2 of apache#13133, depending on apache#13560. Preserve the Java carrier through Velox input streams and lazy output loading, with focused native, real-JVM, and Delta constraint regressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
Hi @zhztheplayer @marin-ma @zhouyuan, could you review #13560? It’s the core-only split from #13133, covering Java throwable preservation and JNI reference lifetime. The Velox integration is in separate PRs, and CI is green. Thanks! |
There was a problem hiding this comment.
🟡 Changes recommended
Carrier allocation failure can discard the original Java throwable and replace it with a bad_alloc-based GlutenException; construction needs a restoration guard and targeted failure coverage.
1 open issue
What changed in this PR
This PR adds backend-neutral transport for original Java throwables across JNI boundaries. It is the core layer of the split implementation; backend-specific propagation and hybrid Java/C++ stack traces remain outside its scope.
Changes:
- Add
JavaExceptionwith shared global-reference ownership and thread-aware cleanup. - Update JNI exception handling to restore direct and standard nested Java carriers while retaining native-error fallback.
- Register focused lifetime and failure-path tests, isolate allocator fault injection, and document the transport contract.
| File | Description |
|---|---|
| docs/developers/NewToGluten.md | Document exception preservation and scope limits. |
| cpp/core/tests/utils/TestJniEnvironment.h | Add a mock JNI environment for ownership and failure tests. |
| cpp/core/tests/JavaExceptionTest.cc | Test lifetime, thread cleanup, nesting, and JNI failures. |
| cpp/core/tests/JavaExceptionAllocationTest.cc | Test diagnostic allocation failure in isolation. |
| cpp/core/tests/CMakeLists.txt | Register both exception test executables. |
| cpp/core/jni/JniError.h | Restore original throwables at JNI exit boundaries. |
| cpp/core/jni/JniCommon.h | Delegate callback exception capture to JavaException. |
| cpp/core/jni/JavaException.h | Define the throwable carrier interface. |
| cpp/core/jni/JavaException.cc | Implement ownership, diagnostics, cleanup, and restoration. |
| cpp/core/CMakeLists.txt | Include the carrier in the core library build. |
Review effort: Balanced
Split layer 2 of apache#13133, depending on apache#13560. Preserve the Java carrier through Velox input streams and lazy output loading, with focused native, real-JVM, and Delta constraint regressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
zhztheplayer
left a comment
There was a problem hiding this comment.
Thanks. Can we have light Java-side test cases to cover the changes?
|
Run Gluten Clickhouse CI on x86 |
Move the four real-JVM cases into gluten-arrow/src/test/java and normal Surefire execution. Enable the explicit jni-test profile in the existing Spark 3.5 Java CI job and transfer its test-only native bridge as a separate artifact. Remove the standalone Java main and CTest jar runner; keep production transport and native entrypoints unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Build the test-only JNI bridge and run its JUnit suite in the existing native/UDF job. Remove the separate test artifact and Spark group-specific path, and add narrow triggers for the Java suite and its build wiring. Keep the tests, Maven profile and production transport unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Move the JNI-only exclusion into a default module profile that appends inherited exclusions. Enabling jni-test disables only that profile instead of clearing the complete Surefire exclusion list. Preserve the existing native loading and CI contracts. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Catch standard JNI-boundary errors by const reference without changing matching or fallback behavior. Restore the diagnostic-allocation test JNI function table with a local nonallocating guard before its stack replacement expires, including during unwinding. Keep catch-all handling out of scope. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Check pending JNI state after direct and nested carrier restoration. Attempt the existing GlutenException fallback only if no Java exception is pending, preserve newer pending errors, and log fallback failure. Cover the failed-restore paths with scoped real-JVM fault injection and name the unchanged diagnostic local-frame capacity. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Guard the direct JavaException handler before restoring the original throwable, matching the nested path. Add real-JVM direct and nested regression coverage for a newer exception installed during carrier propagation before JNI_METHOD_END. Keep existing restoration-failure fallback and native-only behavior unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Track nested guarded JNI entries on the current thread without retaining throwables or allocating guard state. Failed carrier capture restores pending Java state only within such an entry; otherwise clear it before native failure propagates. Preserve successful cross-thread carrier transport, verify worker reuse and nested reentry, and clarify diagnostics and public iterator cause-chain behavior. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Clarify that a pending Java allocation error from failed global-reference capture is preserved only within a guarded JNI entry; native-only workers follow the clearing contract above. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
c7a7586 to
8917db5
Compare
There was a problem hiding this comment.
🔵 Needs a closer look
Cross-thread JNI cleanup and allocation-failure recovery alter the shared JNI contract, requiring human validation of native/JVM CI evidence, including cross-library entry tracking, beyond static review.
No open issues 🎉
Review effort: Balanced
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
Thanks @rdtr. I sent the changes and CI is green |
Split layer 2 of apache#13133, depending on apache#13560. Preserve the Java carrier through Velox input streams and lazy output loading, with focused native, real-JVM, and Delta constraint regressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Split layer 2 of apache#13133, depending on apache#13560. Preserve the Java carrier through Velox input streams and lazy output loading, with focused native, real-JVM, and Delta constraint regressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Split layer 2 of apache#13133, depending on apache#13560. Preserve the Java carrier through Velox input streams and lazy output loading, with focused native, real-JVM, and Delta constraint regressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Split layer 2 of apache#13133, depending on apache#13560. Preserve the Java carrier through Velox input streams and lazy output loading, with focused native, real-JVM, and Delta constraint regressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Split layer 2 of apache#13133, depending on apache#13560. Preserve the Java carrier through Velox input streams and lazy output loading, with focused native, real-JVM, and Delta constraint regressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…NOT_NULL_ASSERT_VIOLATION exception ## What changes are proposed in this pull request? On Spark 4.x, Spark fails a write of a null into a non-nullable field with [NOT_NULL_ASSERT_VIOLATION](https://github.com/apache/spark/blob/v4.2.0/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryExecutionErrors.scala#L3090-L3097), while the Velox backend failed it with a [GlutenException](https://github.com/apache/gluten/blob/31fb4dad58e7339ac4f4b820931d648160dc4746/gluten-core/src/main/java/org/apache/gluten/exception/GlutenException.java) carrying Velox's own message ([AssertNotNull.cpp](https://github.com/IBM/velox/blob/6deac80271569277bf54b6d04547620c17438348/velox/functions/sparksql/AssertNotNull.cpp#L27)). With this change, the Velox backend fails with Spark's exception on Spark 4.0, 4.1 and 4.2. | Inserted value | Spark 4.2.0 without Gluten | Gluten before this change | Gluten after this change | |---|---|---|---| | `1` into `INT NOT NULL` | Inserted | Inserted | Inserted | | `NULL` into `INT NOT NULL` | `NOT_NULL_ASSERT_VIOLATION` | `GlutenException` | `NOT_NULL_ASSERT_VIOLATION` | [apache#11685](apache#11685) moved Spark's not-null check into Velox. Before it, Spark ran the check and threw its own exception. Since then, Spark's tests for this error have been excluded or replaced with Gluten copies that look for Velox's text. With this change, those tests run again on Spark 4.0, 4.1 and 4.2, and their copies are removed, except for the update tests below. Code that matches on the NOT_NULL_ASSERT_VIOLATION condition now gets it under Gluten, as it does in Spark. Velox's message does not name the field, so the exception carries the empty field path that [Spark uses](https://github.com/apache/spark/blob/v4.2.0/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/objects/objects.scala#L1961) when it has none. The three [update with NOT NULL checks](https://github.com/apache/spark/blob/v4.2.0/sql/core/src/test/scala/org/apache/spark/sql/connector/UpdateTableSuiteBase.scala#L855) tests check the field path, so they stay excluded. Spark 4.2's three [update with constraint violation and transactional checks](https://github.com/apache/spark/blob/v4.2.0/sql/core/src/test/scala/org/apache/spark/sql/connector/UpdateTableSuiteBase.scala#L1096) tests stay excluded too. In these updates, the output of the pipeline that fails feeds a second native pipeline. Since [apache#13560](apache#13560), that second pipeline's [translateException](https://github.com/apache/gluten/blob/ec710f1cd7bd474de1ad5085299fef01715c499a/gluten-arrow/src/main/java/org/apache/gluten/vectorized/ColumnarBatchOutIterator.java#L146-L164) wraps Spark's exception in a `GlutenException`, as it does every exception it does not translate itself. The Gluten copies of the update tests, in [GlutenUpdateTableSuiteBase](https://github.com/apache/gluten/blob/31fb4dad58e7339ac4f4b820931d648160dc4746/gluten-ut/spark42/src/test/scala/org/apache/spark/sql/connector/GlutenUpdateTableSuiteBase.scala#L28) and the Spark 4.0 and 4.1 [GlutenGroupBasedUpdateTableSuite](https://github.com/apache/gluten/blob/31fb4dad58e7339ac4f4b820931d648160dc4746/gluten-ut/spark40/src/test/scala/org/apache/spark/sql/connector/GlutenGroupBasedUpdateTableSuite.scala#L22), now accept any exception whose causes carry Velox's message. On Spark 3.4 and 3.5, Spark throws a [NullPointerException](https://github.com/apache/spark/blob/v3.5.5/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/objects/objects.scala#L1835-L1844) whose message names the field instead, so the Velox backend keeps its exception there. Part of apache#11912 ## How was this patch tested? ### Reproduction 1. Clone the repo and check out the base commit: ```bash git clone https://github.com/apache/gluten.git cd gluten git checkout 31fb4da ``` 2. Build the native libraries and the Spark 4.2 bundle jar: ```bash docker run --rm -v "$PWD":/work/gluten:z apache/gluten:centos-9-jdk8 bash -c ' source /opt/rh/gcc-toolset-12/enable export VELOX_BUILD_SHARED=ON cd /work/gluten ./dev/builddeps-veloxbe.sh --run_setup_script=OFF --build_arrow=OFF export JAVA_HOME=/usr/lib/jvm/java-17-openjdk ./build/mvn clean install -Pbackends-velox -Pspark-4.2 -Pscala-2.13 -Pjava-17 -DskipTests ' ``` 3. Fetch Spark 4.2.0: ```bash curl -sSL https://archive.apache.org/dist/spark/spark-4.2.0/spark-4.2.0-bin-hadoop3.tgz | tar -xz ``` 4. Write two queries that insert from a Parquet table into a NOT NULL column. Spark 4.2 checks NOT NULL on file source inserts only with [spark.sql.fileSource.insert.enforceNotNull](https://github.com/apache/spark/blob/v4.2.0/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala#L5170-L5176), and the queries turn off ANSI mode, which Gluten falls back to Spark for: ```bash cat > fits.sql <<'EOF' SET spark.sql.ansi.enabled=false; SET spark.sql.fileSource.insert.enforceNotNull=true; DROP TABLE IF EXISTS src; DROP TABLE IF EXISTS t; CREATE TABLE src USING parquet AS SELECT 1 AS i; CREATE TABLE t (i INT NOT NULL) USING parquet; INSERT INTO t SELECT i FROM src; SELECT i FROM t; EOF cat > null.sql <<'EOF' SET spark.sql.ansi.enabled=false; SET spark.sql.fileSource.insert.enforceNotNull=true; DROP TABLE IF EXISTS src; DROP TABLE IF EXISTS t; CREATE TABLE src USING parquet AS SELECT CAST(NULL AS INT) AS i; CREATE TABLE t (i INT NOT NULL) USING parquet; INSERT INTO t SELECT i FROM src; EOF ``` 5. Run each query with Gluten, and print the exception it fails with and Velox's reason, if any: ```bash docker run --rm -v "$PWD":/work/gluten:z apache/gluten:centos-9-jdk8 bash -c ' export JAVA_HOME=/usr/lib/jvm/java-17-openjdk cd /work/gluten BUNDLE=$(ls package/target/gluten-velox-bundle-spark4.2_2.13-linux_amd64-*.jar) for q in fits.sql null.sql; do spark-4.2.0-bin-hadoop3/bin/spark-sql --master "local[2]" \ --jars "$BUNDLE" --driver-class-path "$BUNDLE" \ --conf spark.plugins=org.apache.gluten.GlutenPlugin \ --conf spark.memory.offHeap.enabled=true \ --conf spark.memory.offHeap.size=4g \ --conf spark.shuffle.manager=org.apache.spark.shuffle.sort.ColumnarShuffleManager \ -f "$q" 2>err.log grep -m 1 -E "^org\.apache\.[a-z.]+\.[A-Za-z]+Exception: " err.log grep -m 1 "^Reason:" err.log done ' ``` On the base commit, the null fails with a `GlutenException` that wraps Velox's error: ``` spark.sql.ansi.enabled false spark.sql.fileSource.insert.enforceNotNull true 1 spark.sql.ansi.enabled false spark.sql.fileSource.insert.enforceNotNull true org.apache.gluten.exception.GlutenException: org.apache.gluten.exception.GlutenException: Exception: VeloxUserError Reason: Null value appeared in non-nullable field ``` On this pull request's branch, rerunning steps 2 and 5 gives Spark's exception, with Velox's error kept as its cause: ``` spark.sql.ansi.enabled false spark.sql.fileSource.insert.enforceNotNull true 1 spark.sql.ansi.enabled false spark.sql.fileSource.insert.enforceNotNull true org.apache.spark.SparkRuntimeException: [NOT_NULL_ASSERT_VIOLATION] NULL value appeared in non-nullable field: Reason: Null value appeared in non-nullable field ``` Spark without Gluten, which is step 5's `spark-sql` command keeping only `--master`, fails with the same exception: ``` spark.sql.ansi.enabled false spark.sql.fileSource.insert.enforceNotNull true 1 spark.sql.ansi.enabled false spark.sql.fileSource.insert.enforceNotNull true org.apache.spark.SparkRuntimeException: [NOT_NULL_ASSERT_VIOLATION] NULL value appeared in non-nullable field: ``` Spark's message continues with the field, `i`, where Gluten's message has none: ```bash grep -m 1 -A 2 "^org.apache.spark.SparkRuntimeException" err.log ``` ``` org.apache.spark.SparkRuntimeException: [NOT_NULL_ASSERT_VIOLATION] NULL value appeared in non-nullable field: i If the schema is inferred from a Scala tuple/case class, or a Java bean, please try to use scala.Option[_] or other nullable types (such as java.lang.Integer instead of int/scala.Int). SQLSTATE: 42000 ``` ### Automated tests Inside the `apache/gluten:centos-9-jdk8` image, with JDK 17 and `SPARK_ANSI_SQL_MODE=false`, which [Gluten's CI sets](https://github.com/apache/gluten/blob/31fb4dad58e7339ac4f4b820931d648160dc4746/.github/workflows/velox_backend_x86.yml#L65-L66), the suites that held the excluded tests and the Gluten copies pass on Spark 4.0: ```bash SPARK_ANSI_SQL_MODE=false ./build/mvn -ntp -B clean test -Pspark-4.0 -Pscala-2.13 -Pjava-17 -Pbackends-velox -Pspark-ut -pl gluten-ut/spark40 -am -DargLine="-Dspark.test.home=/opt/shims/spark40/spark_home/" -Dtest=none -DfailIfNoTests=false -DwildcardSuites=org.apache.spark.sql.GlutenRuntimeNullChecksV2Writes,org.apache.spark.sql.connector.GlutenDataSourceV2SQLSuiteV1Filter,org.apache.spark.sql.sources.GlutenInsertSuite,org.apache.spark.sql.connector.GlutenGroupBasedUpdateTableSuite,org.apache.spark.sql.connector.GlutenDeltaBasedMergeIntoTableSuite,org.apache.spark.sql.connector.GlutenDeltaBasedMergeIntoTableUpdateAsDeleteAndInsertSuite,org.apache.spark.sql.connector.GlutenGroupBasedMergeIntoTableSuite,org.apache.spark.sql.connector.GlutenDeltaBasedUpdateAsDeleteAndInsertTableSuite,org.apache.spark.sql.connector.GlutenDeltaBasedUpdateTableSuite -Dspotless.check.skip=true -Dscalastyle.skip=true -Dcheckstyle.skip=true ``` ``` GlutenRuntimeNullChecksV2Writes: … - NOT NULL checks for atomic top-level fields (byName) … GlutenDataSourceV2SQLSuiteV1Filter: … - CreateTableAsSelect: nullable schema … GlutenInsertSuite: … - SPARK-24583 Wrong schema type in InsertIntoDataSourceCommand … GlutenDeltaBasedMergeIntoTableSuite: … - merge with NOT NULL checks … Tests: succeeded 567, failed 0, canceled 0, ignored 38, pending 0 All tests passed. ``` Spark 4.1 runs the same command with `-Pspark-4.1`, `gluten-ut/spark41` and `/opt/shims/spark41/spark_home/`: ``` Tests: succeeded 860, failed 0, canceled 0, ignored 38, pending 0 All tests passed. ``` Spark 4.2 runs it with `-Pspark-4.2`, `gluten-ut/spark42` and `/opt/shims/spark42/spark_home/`: ``` GlutenInsertSuite: … - SPARK-55716: V1 INSERT rejects null into NOT NULL column for file sources … GlutenGroupBasedMergeIntoTableSuite: … - merge with NOT NULL checks … GlutenDeltaBasedUpdateTableSuite: … - Gluten - update with constraint violation and transactional checks … Tests: succeeded 813, failed 0, canceled 0, ignored 41, pending 0 All tests passed. ``` On Spark 3.5, where the Gluten copies stay, [GlutenRuntimeNullChecksV2Writes](https://github.com/apache/gluten/blob/31fb4dad58e7339ac4f4b820931d648160dc4746/gluten-ut/spark35/src/test/scala/org/apache/spark/sql/GlutenRuntimeNullChecksV2Writes.scala#L28) passes with JDK 8: ```bash ./build/mvn -ntp -B clean test -Pspark-3.5 -Pbackends-velox -Pspark-ut -pl gluten-ut/spark35 -am -DargLine="-Dspark.test.home=/opt/shims/spark35/spark_home/" -Dtest=none -DfailIfNoTests=false -DwildcardSuites=org.apache.spark.sql.GlutenRuntimeNullChecksV2Writes -Dspotless.check.skip=true -Dscalastyle.skip=true -Dcheckstyle.skip=true ``` ``` Tests: succeeded 8, failed 0, canceled 0, ignored 14, pending 0 All tests passed. ``` The change also compiles against Spark 3.4: ```bash ./build/mvn -ntp -B test-compile -Pbackends-velox -Pspark-ut -Pspark-3.4 -pl gluten-ut/spark34 -am ``` ``` [INFO] BUILD SUCCESS ``` ## Was this patch authored or co-authored using generative AI tooling? Generated-by: Co-authored with Claude Code (claude-opus-5-5)
Split layer 2 of apache#13133, depending on apache#13560. Preserve the Java carrier through Velox input streams and lazy output loading, with focused native, real-JVM, and Delta constraint regressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>


What changes are proposed in this pull request?
Java callback failures currently become text in
checkExceptionand return as a newGlutenException. This loses the original exception type, cause chain, and Spark/Delta metadata. This patch preserves the same Java throwable object at the JNI return boundary instead. Existing public iteratorExceptionwrappers remain unchanged; inspect their cause chain rather than assuming the original is the top-level exception.gluten::JavaExceptionholds a shared JNI global reference across native copies,std::exception_ptr, and thread handoffs. Cleanup uses the current thread's JNI environment and detaches only threads it attached.checkExceptioncaptures the throwable;JNI_METHOD_ENDrestores it through direct or standard nested exceptions. Successful native propagation keeps JNI clear until the return boundary. Native-only failures retain the existingGlutenExceptionfallback.Scope: Backend-neutral JNI transport, layer 1 of 3. Velox iterator and memory-callback integration follow in #13561 and #13563; #13133 is the combined reference. This layer alone does not protect the full Velox driver path, translate native errors, or merge Java/C++ stack traces.
How was this patch tested?
jni-testMaven path is unchanged.These are focused core/JNI checks; this PR does not claim end-to-end Velox or Delta coverage.
Was this patch authored or co-authored using generative AI tooling?
Generated-by: GitHub Copilot 1.0.102-0.unstable.r40949665530.gab1eef5 (model: gpt-6-astra)