Skip to content

[GLUTEN-13685][VL] Raise Spark DIVIDE_BY_ZERO error for native divide by zero - #13697

Open
Abhinav-Agarwal021 wants to merge 8 commits into
apache:mainfrom
Abhinav-Agarwal021:abhinagarwal/spark-error-code-poc
Open

Abhinav-Agarwal021 wants to merge 8 commits into
apache:mainfrom
Abhinav-Agarwal021:abhinagarwal/spark-error-code-poc

Conversation

@Abhinav-Agarwal021

@Abhinav-Agarwal021 Abhinav-Agarwal021 commented Nov 20, 2026 •

Copy link
Copy Markdown

What changes are proposed in this pull request?

Proof of concept for #13685 and facebookincubator/velox#20483, as suggested by @rui-mo: one function, end to end.

Depends on facebookincubator/velox#20514. With that change, Velox attaches the Spark error condition to a user error as the error code SPARK:<condition>, and checked_divide reports SPARK:DIVIDE_BY_ZERO.

Why

With ANSI on, a native divide by zero fails with a generic SparkException around the Velox error, instead of Spark's DIVIDE_BY_ZERO error. Applications and tools that check the Spark error condition or SQLSTATE handle the same query differently with and without Gluten.

What

  • The JNI boundary passes the native error code to Java with the GlutenException it raises for a native error. The Velox backend tells cpp/core how to read the code from a VeloxException.
  • NativeErrorTranslator maps a supported code to the matching Spark exception, with the native error as its cause. Only DIVIDE_BY_ZERO is supported for now. The supported codes are constants in NativeErrorCodes.
  • Only the exact GlutenException raised at the JNI boundary is translated. Java callback failures and Java exceptions that wrap a native error keep the existing handling.
  • An unsupported SPARK: code logs a warning and keeps the native error, so behavior is unchanged.
  • ColumnarBatchOutIterator.translateException calls the translator first.

Before (ANSI on, SELECT a / zero FROM ansi_demo with zero = 0):

org.apache.spark.SparkException: Job aborted due to stage failure: ...
org.apache.gluten.exception.GlutenException: ... Exception: VeloxUserError
Error Source: USER
Error Code: INVALID_ARGUMENT
Reason: division by zero

After, the same condition and SQLSTATE as vanilla Spark:

ArithmeticException: [DIVIDE_BY_ZERO] Division by zero. Use `try_divide` to tolerate divisor being 0 and return NULL instead. If necessary set "spark.sql.ansi.enabled" to "false" to bypass this error. SQLSTATE: 22012

Known gaps, for discussion:

  • No query context (the == SQL == fragment) yet. The exception has an empty query context rather than a null entry, which PySpark cannot read.
  • Only ColumnarBatchOutIterator is wired.
  • One condition only.
  • Per @philo-he's comment on velox#20483: a single Gluten-defined fallback condition for all other Velox user errors would fit in this translator as a follow-up.

How was this patch tested?

  • Unit tests check that the error code reaches Java at the JNI boundary (with a code, without one, and when reading the code fails). They also check that only the boundary GlutenException is translated and that the Spark exception has the right condition, SQLSTATE, message parameters, cause and an empty query context.
  • ArithmeticAnsiValidateSuite checks that a divide by zero that runs natively raises DIVIDE_BY_ZERO with SQLSTATE 22012, on Spark 3.x (wrapped in a SparkException) and 4.x (thrown as it is). This needs the Velox PR.
  • Verified end to end on a Spark 4.2 cluster with both changes (output above), including from PySpark.
  • The APIs used (SparkArithmeticException(String, Map, Array[QueryContext], String), QueryExecutionErrors.toSQLConf) exist in Spark 3.4, 3.5 and 4.x. NativeErrorTranslatorSuite passes locally with Spark 3.5 and 4.1.

Was this patch authored or co-authored using generative AI tooling?

Generated-by: GitHub Copilot CLI 1.0.114

… by zero

Proof of concept for apache#13685 and facebookincubator/velox#20483.
Velox reports the Spark error condition as the error code
"SPARK:<condition>". Gluten now reads it and raises the matching Spark
exception, so Spark shows the real error instead of wrapping it in
"Job aborted due to stage failure".

- Add NativeErrorTranslator. It reads the first
  "Error Code: SPARK:<condition>" line of a native error, walking at most
  16 causes, and builds the Spark exception with the native error as its
  cause. Only DIVIDE_BY_ZERO is supported for now. Other SPARK: codes log
  a warning and keep the native error.
- ColumnarBatchOutIterator.translateException calls it first. Errors
  without a SPARK: code are unchanged.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

*/
def translate(error: Throwable): RuntimeException = {
val condition = Iterator
.iterate(error)(_.getCause)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The “finds the error code in a cause” case translates through an arbitrary RuntimeException. If a Java callback throws its own exception with a Velox divide-by-zero error as its cause, this turns the callback failure into a SparkArithmeticException. That changes which catch block runs. Could we follow causes only through wrappers we know Gluten added for native errors, and otherwise keep the existing exception handling?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed in e7bfd0e. The translator now only handles the GlutenException that the JNI boundary raises for a native error (exact class, no cause) and reads only its message. Java callback failures are restored as the original Java exception, so they keep the existing handling, as do Java wrappers around a native error; the cause chain is no longer searched. Added tests for both cases.

@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

…boundary

Addresses review feedback on apache#13697: searching the whole cause chain could
turn a Java callback failure that has a native divide-by-zero error as its
cause into a SparkArithmeticException, which changes which catch block runs.

NativeErrorTranslator now translates an error only when it is the
GlutenException that the JNI boundary raises for a native error: exactly
that class, with no cause. It reads only that exception's message. Java
callback failures restored at the JNI boundary, Java-side wrappers around
a native error, and other exception classes keep the existing handling.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 97f7e7ed-6354-46bf-ba5b-e1a7c86c0246
@Abhinav-Agarwal021
Abhinav-Agarwal021 marked this pull request as ready for review November 23, 2026 06:18
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@rui-mo rui-mo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks.

Option(message)
.flatMap(ErrorCodeLine.findFirstMatchIn(_))
.map(_.group(1))
.filter(code => code.startsWith(SparkErrorCodePrefix))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we extract the errorCode directly in native code when catching the exception thrown by Velox? This would avoid the need to combine the errorCode with the error message and then split them again on the Scala side.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 1a587de. The JNI boundary now reads the error code from the native exception and passes it to Java with a new GlutenException(message, errorCode) constructor. The Velox backend registers how to get the code (VeloxException::errorCode()), so cpp/core does not depend on Velox. The translator reads GlutenException.getErrorCode(), so the Scala side no longer parses the message. JavaExceptionJniTest.nativeErrorCode covers the JNI path.

error != null && error.getClass == classOf[GlutenException] && error.getCause == null

private def toSparkException(condition: String): Option[RuntimeException] = condition match {
case "DIVIDE_BY_ZERO" =>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use constants to manage Spark error codes in Scala. Reuse existing definitions provided by Spark where available; otherwise, define them in a separate file.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. The supported codes are constants in a separate file, NativeErrorCodes (SparkErrorCodePrefix, DivideByZero).

Spark has no constants for its error conditions. They are defined in error-conditions.json, and Spark's own code passes the condition name as a string, for example QueryExecutionErrors.divideByZeroError. The translator builds the same exception as that method: the same condition, message parameters and SQLSTATE.

It no longer calls that method, though. The native error has no query context, and in Spark 4.x divideByZeroError(null) returns Array(null) as the context. PySpark then fails while converting the error (base.py) with AttributeError: 'NoneType' object has no attribute 'contextType'. 21c40c0 builds the exception with an empty context and adds a test for it. It also updates the older divide by zero tests in ArithmeticAnsiValidateSuite: Spark 4.0+ throws the Spark error to the caller as it is, while 3.x wraps it in a SparkException.

Abhinav Agarwal and others added 2 commits November 24, 2026 15:32
…NI boundary

The JNI boundary now reads the error code from the native exception and
passes it to Java with GlutenException(message, errorCode).
NativeErrorTranslator uses GlutenException.getErrorCode() instead of parsing
the error message. The supported codes are constants in NativeErrorCodes, and
the Spark exception comes from QueryExecutionErrors.divideByZeroError.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…e by zero

QueryExecutionErrors.divideByZeroError(null) reports a single null query
context entry in Spark 4.x, and PySpark fails to read it with
"AttributeError: 'NoneType' object has no attribute 'contextType'".
NativeErrorTranslator now builds the SparkArithmeticException with an empty
query context, keeping the same condition, SQLSTATE and message parameters.

Spark 4.0+ passes a user-facing Spark error from a task to the caller as it
is, while Spark 3.x wraps it in a SparkException. The divide by zero tests in
ArithmeticAnsiValidateSuite now find the DIVIDE_BY_ZERO error in the cause
chain, so they pass with both.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@github-actions github-actions Bot added the BOLT label Nov 25, 2026
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@rui-mo rui-mo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Abhinav-Agarwal021 Thank, added some comments.

Consider updating PR_ID to the corresponding Velox PR for development testing.


/**
* Error codes that native code sets on errors that match a Spark error condition. Each code is
* "SPARK:" followed by the Spark error condition.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could you add the reference to Spark json file in the comment?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 9d96a34, the comment now points to Spark's common/utils/src/main/resources/error/error-conditions.json.

* Error codes that native code sets on errors that match a Spark error condition. Each code is
* "SPARK:" followed by the Spark error condition.
*/
object NativeErrorCodes {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we rename this to SparkErrorCodes to make it clear that these are copied from Spark's error codes?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 9d96a34, renamed to SparkErrorCodes.

if (errorCode.startsWith(NativeErrorCodes.SparkErrorCodePrefix)) {
logWarning(
s"Native error has error code $errorCode, which is not supported yet. " +
"Keeping the native error.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we refactor this to reuse the existing message-based error translation as a fallback when the corresponding error code hasn't been added to Velox yet?

This way, we can gradually transition from message-based to error-code-based translation.

b9357c1#diff-4552fdcd7933bcc531cc27ea75dd884ee83077809fe49531728c3b8e325ffbffR161

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 9d96a34. Moved the message-based translation (type conversion and char/varchar length errors from #13639) from ColumnarBatchOutIterator into NativeErrorTranslator. translate uses the error code first and falls back to the message when the error has no code or its code is not supported yet. ColumnarBatchOutIterator.translateException calls it as the single entry point. Once Velox attaches a code for one of those errors, we can drop its message rule.

Comment on lines +26 to +27

val DivideByZero: String = SparkErrorCodePrefix + "DIVIDE_BY_ZERO"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to keep the Spark prefix in Velox to distinguish Spark error codes from those of other engine, such as Presto. Once Gluten receives the error codes, let's strip the Spark prefix on the native side before passing them to Java.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 9d96a34. Velox keeps the SPARK: prefix. VeloxBackend.cc now passes only codes that start with SPARK: and strips the prefix, so Java receives the bare condition, e.g. DIVIDE_BY_ZERO. Codes of other engines are not passed. The prefix constant is removed from Scala.

case NativeErrorCodes.DivideByZero =>
Some(
new SparkArithmeticException(
"DIVIDE_BY_ZERO",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reuse the "DIVIDE_BY_ZERO" defined in ErrorCodes, please avoid hand-writing strings.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 9d96a34, SparkErrorCodes.DivideByZero is used both to match the code and as the error class of the SparkArithmeticException.

RuntimeException sparkEx = NativeErrorTranslator.translate(e);
if (sparkEx != null) {
return sparkEx;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With ANSI on and spark.gluten.sql.ansiFallback.enabled=false, Spark 4.0.2 throws SparkArithmeticException [DIVIDE_BY_ZERO] unwrapped for SELECT a / b AS c FROM div_tab DISTRIBUTE BY c (DAGScheduler.scala#L2928-L2936). In Gluten, the default VeloxResizeBatchesExec before the hash shuffle reads the translated error through ColumnarBatchInIterator. JNI_METHOD_END rethrows it, and the unchanged fallback at lines 165-168 wraps it in GlutenException, so users get Job aborted due to stage failure again (source trace).

Return already-translated Spark exceptions unchanged, at least those from NativeErrorTranslator, as lines 165-166 do for GlutenException. Add a shuffle test that checks the top-level exception on Spark 4.x.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the trace. Fixed in 9d96a34: ColumnarBatchOutIterator.translateException now returns a SparkThrowable runtime exception as-is, before any translation, so the error translated by the nested iterator is no longer wrapped in GlutenException. Added divide by zero before a shuffle throws Spark DIVIDE_BY_ZERO error in ArithmeticAnsiValidateSuite, which runs SELECT a / b AS c FROM div_tab DISTRIBUTE BY c and checks that the top-level exception is SparkArithmeticException on Spark 4.x.

Abhinav Agarwal and others added 2 commits November 26, 2026 12:41
…-code-poc

# Conflicts:
#	cpp/core/jni/JniError.cc
#	gluten-arrow/src/main/java/org/apache/gluten/vectorized/ColumnarBatchOutIterator.java
…e to SparkErrorCodes, message fallback, keep translated errors through shuffle

- VeloxBackend passes only "SPARK:"-prefixed Velox error codes to Java, with the prefix stripped.
- Rename NativeErrorCodes to SparkErrorCodes and reference Spark's error-conditions.json.
- Move the message-based translation from ColumnarBatchOutIterator into NativeErrorTranslator
  as a fallback when an error has no supported error code.
- Return SparkThrowable runtime exceptions as-is in ColumnarBatchOutIterator so translated errors
  are not rewrapped across a shuffle; add a test.
- Point UPSTREAM_VELOX_PR_ID to facebookincubator/velox#20514 for testing.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@github-actions github-actions Bot added the BUILD label Nov 26, 2026
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@Abhinav-Agarwal021

Copy link
Copy Markdown
Author

@rui-mo Thanks for the review. All comments are addressed in 9d96a34 (on top of a merge of main, needed for the message-based translation from #13639). I also set UPSTREAM_VELOX_PR_ID="20514" in ep/build-velox/src/get-velox.sh for testing with facebookincubator/velox#20514; I'll reset it before merge.

…ate[spark]

Check the top-level exception as ArithmeticException with SparkThrowable instead.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 97f7e7ed-6354-46bf-ba5b-e1a7c86c0246
@github-actions

Copy link
Copy Markdown

Run Gluten Clickhouse CI on x86

@Abhinav-Agarwal021

Copy link
Copy Markdown
Author

@rui-mo I have tested the changes locally and the result matched spark

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

BOLT BUILD CORE works for Gluten Core VELOX

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants