Abhinav-Agarwal021 opened a new issue, #13685: URL: https://github.com/apache/gluten/issues/13685
## 1. Summary When a Velox Spark function fails at runtime (overflow under ANSI, duplicate map key, bad date field, ...), Gluten throws a `GlutenException` that carries only text. On Spark 4.x this changes what **users** see, not only what tests see. Spark itself unwraps user-facing errors for this reason ([SPARK-46922](https://issues.apache.org/jira/browse/SPARK-46922)). ``` Vanilla Spark Gluten + Velox (today) ───────────── ────────────────────── SELECT a / zero FROM ansi_demo (ANSI on) │ │ Spark kernel throws Velox kernel throws SparkArithmeticException VeloxUserError [DIVIDE_BY_ZERO] SQLSTATE 22012 "Division by zero" │ │ JNI (text only) ▼ ▼ user sees the typed error ✓ GlutenException (plain text) → driver wraps it: "Job aborted ..." ✗ ``` #13647 is converging on the **test** side (overridable Spark test helpers, shared test copies). That's useful, but it doesn't change user-facing behaviour. This issue proposes a design for the **runtime** side and asks for feedback before anyone writes code. A matching Velox issue will follow for the Velox part. It follows up on @rui-mo's request on #13639 for a broader design discussion. **Words used below** | Term | Meaning | |---|---| | error class (condition) | Spark's error name, e.g. `DIVIDE_BY_ZERO`, returned by `SparkThrowable.getCondition()` | | message parameters | the values filled into the class's message template, e.g. for `DIVIDE_BY_ZERO`, `config="spark.sql.ansi.enabled"` | | raise site | a place in Velox that raises a user error (`VELOX_USER_FAIL`, `Status::UserError`, ...) | | wrapped | Spark replaces the task's exception with `SparkException("Job aborted due to stage failure: ...")` | ## 2. The exact error today The same PySpark query, run first with Gluten + Velox and then on vanilla Spark: ```python spark.conf.set("spark.sql.ansi.enabled", "true") spark.sql("SELECT a / zero FROM ansi_demo").show() ``` **Gluten + Velox** (what the user sees): ```text Py4JJavaError: An error occurred while calling o6922.showString. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 7.0 failed 4 times, most recent failure: Lost task 0.3 in stage 7.0 (TID 27) (... executor 7): org.apache.gluten.exception.GlutenException: org.apache.gluten.exception.GlutenException: Exception: VeloxUserError Error Source: USER ``` **Vanilla Spark** (stack trimmed): ```text Py4JJavaError: An error occurred while calling o6940.showString. : org.apache.spark.SparkArithmeticException: [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 == SQL (line 1, position 8) == SELECT a / zero FROM ansi_demo ^^^^^^^^ at org.apache.spark.sql.errors.QueryExecutionErrors$.divideByZeroError(QueryExecutionErrors.scala) at org.apache.spark.sql.errors.QueryExecutionErrors.divideByZeroError(QueryExecutionErrors.scala) at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage1.processNext(Unknown Source) ... at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala) ... at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala) ``` | | Gluten + Velox | Spark | |---|---|---| | Exception the user catches | `SparkException` ("Job aborted"), wrapping `GlutenException` | `SparkArithmeticException` (also a `java.lang.ArithmeticException`) | | `getCondition()` | `null` | `DIVIDE_BY_ZERO` | | SQLSTATE | none | `22012` | | Message | `Job aborted ... VeloxUserError Error Source: USER`; the reason is only in the nested text | Spark's text, the `try_divide` hint, and the SQL fragment `a / zero` | Three things in this pair support the proposal: 1. **Vanilla Spark builds the error on the executor** (`Executor$TaskRunner.run`), and `DAGScheduler` lets it through untouched. That's the rule in §3. 2. **It's built by `QueryExecutionErrors.divideByZeroError`.** That's exactly the factory a Gluten shim would call (§6.4), so the user would get Spark's own message, not an imitation. 3. **`GlutenException: GlutenException:`.** The error was wrapped twice on the way out. #13148 now prevents this for `GlutenException`, and the same "never re-wrap" rule has to hold for typed Spark errors (§3, gotchas). This breaks: - user code, notebooks, and JDBC / Spark Connect clients that check `getCondition()` or SQLSTATE; - `intercept[ArithmeticException]` and `checkError(condition = ...)` in Spark's tests, which is the root cause of many excludes and copied tests under #11912; - log searches and alerts for error names such as `DIVIDE_BY_ZERO`. ## 3. How Spark decides: show the real error, or wrap it in "Job aborted" Think of the driver as a mail room. Letters stamped with a recognised error class go straight to the user. Anything else gets put inside a "Job aborted" envelope, and the original letter ends up buried in the message text. ``` ① Velox raise site ─► VeloxUserError (C++) ② JNI_METHOD_END ─► ThrowNew(GlutenException, e.what()) cpp/core/jni/JniError.h ③ ClosableIterator.translateException (executor) ◄── last place we can change the type ④ Executor: task fails ─► ExceptionFailure(serialized exception) ─► driver ⑤ DAGScheduler.abortStage: is it a user-facing SparkThrowable? yes ─► user sees it as is ✓ no ─► new SparkException("Job aborted due to stage failure: ...", cause) ✗ ``` Source: [`DAGScheduler.scala` @ 1a4b749](https://github.com/apache/spark/blob/1a4b749de447cc6a90aa625bb04d32a9a49238cc/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala#L3311-L3319). The same code is on `branch-4.0`; `branch-3.5` always wraps. ```scala val finalException = exception.collect { // If the error is user-facing (defines error class and is not internal error), we don't // wrap it with "Job aborted" and expose this error to the end users directly. case st: Exception with SparkThrowable if st.getCondition != null && !SparkThrowableHelper.isInternalError(st.getCondition) => st }.getOrElse { new SparkException(s"Job aborted due to stage failure: $reason", cause = exception.orNull) } ``` | # | Check | Where | `GlutenException` today | |---|---|---|---| | 1 | The **top-level** task exception is an `Exception` that implements `SparkThrowable`. The cause chain is not inspected. | `DAGScheduler` | ✗ `extends RuntimeException` | | 2 | `getCondition()` is not null. | `DAGScheduler` | ✗ no condition | | 3 | The condition does not start with `INTERNAL_ERROR`. | `SparkThrowableHelper.isInternalError` | ✗ (n/a) | | 4 | The translation happens **on the executor**, before the task failure is reported (step ③). | `Executor` → `TaskEndReason` | — no translation for these errors | | 5 | The exception can be serialized. If serialization fails, the driver receives none and wraps. | `Executor`, `TaskEndReason` | ✓ | **Passing ≠ correct.** Any non-internal class passes checks 1–3. Matching Spark also needs the **right** class and its **parameters**. **Why not just make `GlutenException` implement `SparkThrowable`?** It's created from text at the JNI boundary and doesn't know which Spark error it is. Any fixed class would be wrong for most errors, and an `INTERNAL_ERROR*` class would still be wrapped. **Gotchas** - **Re-wrapping:** if any layer above step ③ wraps the typed error again (for example in a new `GlutenException`), check 1 fails again. #13148 already stops `translateException` from re-wrapping `GlutenException`; the same rule must hold for typed Spark errors. - **Last attempt wins:** the driver reports the exception from the task attempt that hit `spark.task.maxFailures`, so every attempt must translate. - **Translating on the driver is too late:** by step ⑤ the decision has already been made. ## 4. Requirements | # | Requirement | |---|---| | R1 | Users get the same error class, SQLSTATE and message parameters as vanilla Spark. | | R2 | Translation happens on the executor, and the result passes checks 1–5 above. | | R3 | No dependence on free English message text. | | R4 | The original native error is kept as the cause, so diagnostics aren't lost. | | R5 | If translation fails or the class is unknown on that Spark version, the original error is returned (never worse than today). | | R6 | `TRY` / `try_*` / `try_cast` keep returning NULL, with no extra cost. | | R7 | No cost on rows that succeed. | | R8 | No re-execution of tasks (no side effects). | | R9 | Presto behaviour and messages in shared Velox code are unchanged. | | R10 | Works on every Spark version Gluten supports; classes missing on old versions fall back per R5. | ## 5. Options: C (reason marker) or D (typed carrier) Both options share the same **JVM half**: a per-Spark-version shim that turns `(condition, params)` into the real Spark exception using Spark's `QueryExecutionErrors` factories. They also share the same **per-raise-site work**: each Velox Spark function must say *which* Spark error it raises and with which parameters. They differ only in **how `(condition, params)` travels from Velox to the JVM**. ``` C Reason marker ★ Velox "DIVIDE_BY_ZERO|k=<b64>" ──JNI (text, unchanged)──► parser ──► factory D Typed carrier Velox ex{cond, params} ──JNI builds Java ex──► factory (core + JNI change) ``` | | **C ★ Reason marker** | D Typed carrier | |---|---|---| | Meets R1–R10 | ✓ | ✓ | | Velox change | 1 helper + raise sites | **core `VeloxException`** fields + raise sites | | Gluten change | translator + shims | **JNI exit of every call** + shims | | Survives Velox rewording | ✓ | ✓ | | Cost on failing rows | one short string; skipped inside TRY | larger exception objects; skipped inside TRY | | Must survive re-wrapping inside Velox | no (it's the `Reason:` text) | yes (new fields must be copied on every re-throw) | | Size of the first PR | small | large, touches shared Velox core | **Related work.** #13135 (casts), #13639 (`EXCEED_LIMIT_LENGTH`) and #12544 (`INVALID_BITMAP_POSITION`) each fix one family by matching Velox's message text. That works for one fixed message, but it doesn't scale: `Arithmetic overflow: a + b` doesn't say `integer` vs `long`, `division by zero` is used for both `/` and `%`, and an upstream rewording silently breaks the mapping. This proposal gives those PRs one shared contract instead. It builds on #13148 (no re-wrapping of `GlutenException`) and #13560 (Java throwables survive JNI), and uses the existing `ClosableIterator.translateException` hook. ## 6. Proposal: Option C now, with a contract that lets us move to D later ### 6.1 Contract A Velox **Spark** raise site that knows it is raising a Spark user error supplies `(condition, params)`, using names from Spark's `error-conditions.json`: ```text condition = "DIVIDE_BY_ZERO" params = {config: "\"spark.sql.ansi.enabled\""} ``` Spark fills the rest of the message (the `try_divide` hint, SQLSTATE `22012`) from its own template, so Velox never copies Spark's text. The contract doesn't depend on the transport: ``` Now: C transport ─┐ ├──► same raise sites, same shims, same tests Later: D transport ─┘ (only the helper and the JNI boundary change) ``` ### 6.2 End-to-end flow ``` VELOX JNI GLUTEN (executor) ───── ─── ───────────────── a / zero (divisor is 0) │ ▼ throwSparkError("DIVIDE_BY_ZERO", {config}) │ still a VeloxUserError → TRY still returns NULL (R6) ▼ Reason: DIVIDE_BY_ZERO|config=InNwYXJrLnNxbC5hbnNpLmVuYWJsZWQi │ └──────────────────────────► JNI_METHOD_END ──► ClosableIterator.translateException (unchanged) │ parse the primary "Reason:" line only ▼ ① shim(cond, params) ─► QueryExecutionErrors.* ─► typed error ✓ ② no factory on this Spark version ─► SparkRuntimeException(cond, params) ~ ③ anything fails ─► the original GlutenException (R5) │ original kept as the cause (R4) ▼ SparkArithmeticException [DIVIDE_BY_ZERO] │ DAGScheduler passes it through ▼ user / test ✓ ``` ### 6.3 Velox side: one helper, e.g. `velox/functions/sparksql/SparkErrors.h` - `throwSparkError(condition, params)` builds `CONDITION|key=<base64>|key=<base64>` and raises it as an ordinary `VeloxUserError`. - **Base64 values**, so `|`, `=` and newlines in values (column names, strings) can never break the format. - **A single `Reason:` line.** Today `VELOX_USER_RETURN` plus `EvalCtx::setStatus` produce `Reason: Reason: ...` (visible in the example above). The helper must return `Status::UserError("{}", marker)` (or `VELOX_USER_FAIL("{}", marker)`) so the marker is the whole reason. - **Free inside TRY:** when `threadSkipErrorDetails()` is set (inside `TRY` / `try_*` / `try_cast`), the helper returns a bare user error and builds no string, the same as today's raise sites. ### 6.4 Gluten side - **Parser:** accepts `NAME(.SUBNAME)*|k=v|...` on the primary `Reason:` line only. Values are split on the **first** `=` and Base64-decoded. - **Shim per Spark version:** calls Spark's `QueryExecutionErrors` factories, as #13135 and #13639 do. It lives in `org.apache.spark.sql` because the factories are `private[sql]`. When a class has subclasses, it calls the factory with the top-level name and Spark picks the subclass. - **Fallback:** an unknown class or a decode failure → log a warning → return the original exception (R5). - **Logging:** `Translated native error to <cond>` (warn, once per task); `<cond> not translatable on Spark <ver>` (warn); parameter values at debug level only. ### 6.5 Security: user data can't forge an error class Only the **primary `Reason:` line** is parsed. A string from user data that happens to look like a marker (for example in `Context:` / `Expression:`) is ignored: ``` Exception: VeloxUserError Error Source: USER Reason: DIVIDE_BY_ZERO|config=InNwYXJrLnNxbC5hbnNpLmVuYWJsZWQi ◄── only this line is parsed Expression: ... Context: Top-level Expression: concat('x', 'DIVIDE_BY_ZERO|a=b') ◄── user data: ignored ``` Spark's own factories build the final message, so Velox can't inject message text either. ### 6.6 Shared Presto/Spark code (R9) - Shared helpers (such as checked arithmetic or decimal utilities) **don't name Spark classes**. They return a failure (`Status` / `Expected`), and the **Spark** caller attaches the Spark class. - Casts use the existing Spark hook (`SparkCastHooks`). - A template parameter only where the caller can't attach the class without a performance cost. - No global "dialect" flag. ### 6.7 C vs D, side by side ``` OPTION C (reason marker) OPTION D (typed carrier) Velox raise VELOX_USER_FAIL("{}", throw SparkUserError{ site "DIVIDE_BY_ZERO|config=<b64>") condition, params } │ │ Velox core VeloxUserError (unchanged) VeloxException + new fields (must survive re-wrapping) │ │ JNI exit JNI_METHOD_END (unchanged) JNI_METHOD_END (changed, every call) │ │ Java GlutenException(text) → parse Java carrier → read fields └──────────────► (condition, params) ◄───────────┘ │ same per-version shim → typed Spark error ``` We suggest **C first**: it needs no core Velox or JNI change and runs only on the failure path. D is a clean follow-up, possibly building on #13560/#13135, and it can replace C's transport without touching raise sites or shims. ## 7. How many error classes do we need? **About 30**, spread over hundreds of raise sites. Each class needs **one** shim case on the JVM. Not every raise site needs one: | Raise-site type | Example | Action | |---|---|---| | (a) bad **value** in a row | overflow, bad date field, duplicate map key | needs a class (this is the work) | | (b) bad **constant** argument | invalid pattern or format | Spark usually rejects at planning; check plan-time validation | | (c) internal invariant | `VELOX_CHECK`, `VeloxRuntimeError` | stays internal; wrapping is correct | | Phase | Error classes | |---|---| | 1. ANSI arithmetic | `ARITHMETIC_OVERFLOW`, `DIVIDE_BY_ZERO`, `REMAINDER_BY_ZERO`, `INTERVAL_ARITHMETIC_OVERFLOW`, `INTERVAL_DIVIDED_BY_ZERO`, `NUMERIC_VALUE_OUT_OF_RANGE` | | 2. Datetime, maps, arguments | `DATETIME_OVERFLOW`, `DATETIME_FIELD_OUT_OF_BOUNDS`, `NULL_MAP_KEY`, `DUPLICATED_MAP_KEY`, `INVALID_PARAMETER_VALUE` | | 3. Cast (aligned with #13135) | `CAST_INVALID_INPUT`, `CAST_OVERFLOW` | | 4. Collections, parsing, datetime | `INVALID_ARRAY_INDEX`, `INVALID_ARRAY_INDEX_IN_ELEMENT_AT`, `INVALID_INDEX_OF_ZERO`, `CANNOT_PARSE_TIMESTAMP`, `INVALID_DATETIME_PATTERN`, `INVALID_FRACTION_OF_SECOND`, `ILLEGAL_DAY_OF_WEEK`, `INVALID_TIMEZONE`, `CONVERSION_INVALID_INPUT`, `COLLECTION_SIZE_LIMIT_EXCEEDED` | | 5. Not ANSI-specific | `NOT_NULL_ASSERT_VIOLATION`, `USER_RAISED_EXCEPTION` (for `raise_error` / `assert_true`), `EXCEED_LIMIT_LENGTH` (#13639), `MALFORMED_RECORD_IN_PARSING`, `INVALID_URL`, `INVALID_UTF8_STRING`, `INVALID_REGEXP_REPLACE`, `INVALID_BITMAP_POSITION` (#12544) | That's 31 classes. Seven of them have subclasses (for example `DATETIME_FIELD_OUT_OF_BOUNDS.WITH_SUGGESTION`), which is why the parser accepts `NAME.SUB`. Each phase would be one Velox PR (helper calls at Spark raise sites) followed by one Gluten PR (shim cases plus re-enabling the matching excluded tests). The exact list for each phase would come from walking the type-(a) raise sites in `velox/functions/sparksql` and matching each one to the `QueryExecutionErrors` factory Spark calls for the same expression. ## 8. What about `USER_RAISED_EXCEPTION` as an interim? | Pros | Cons | |---|---| | Passes checks 1–3, so users see the message instead of "Job aborted" | It's the wrong class: `USER_RAISED_EXCEPTION` is for `raise_error`, not overflow | | No Velox change | `checkError` tests still fail; tools that branch on the class get a misleading answer | | | Users see the class change again when the precise mapping lands | We suggest it at most as an **opt-in config, off by default**, applied only to `VeloxUserError` (never to internal errors), not as the default. ## 9. Tests | Layer | Test | |---|---| | Velox | the marker text per raise site; `try_*` still returns NULL and builds no text; ANSI-off results unchanged; Presto tests unchanged | | Gluten unit | the parser (valid, subclassed, malformed, lowercase, `.X`, `X.`); Base64 decode of bad input; one shim case per class per Spark version; the fallback to the original error | | Envelope round trip | real Velox error text → single `Reason: COND\|...` line → parsed (guards against `Reason: Reason:`) | | Scheduler round trip | per class: run a failing query, catch at the driver, and assert the **top-level** exception's class, condition and SQLSTATE, and that it is **not** `SparkException("Job aborted ...")`; this covers serialization and re-wrapping | | Spark UT | re-enable the excluded / copied tests for that family (#11912) | | Performance | microbenchmark of `checked_add` / `cast` at 0%, 1% and 100% failing rows, inside and outside `try`: no difference within noise inside `try` and at 0% | ## 10. Risks | Risk | Mitigation | |---|---| | A layer above `translateException` re-wraps the typed error | the scheduler round-trip test per class; review rule: never wrap a `SparkThrowable` in `GlutenException` | | Native errors raised outside the iterators that call `translateException` | list every JNI entry point that can evaluate expressions, and translate there too | | Wrong class chosen at a raise site | review each phase's raise site → class → factory table against Spark's code for the same expression | | Velox and Gluten merge order | Velox first: on its own, the Velox change only alters the reason text | | Missing SQL query context (`== SQL (line 1, position 8) ==`) | follow-up: carry expression origin through Substrait | | Spark 3.x always wraps | the typed error is still the cause; tests on 3.x check the cause chain | ## 11. Open questions 1. Is the community OK with Gluten matching Spark's error class on Spark 4.x (as #13135 already does for casts), rather than only adapting test checkers? 2. Transport: Option C (marker) first, then D? Or straight to D, building on #13560/#13135? 3. Velox: is it acceptable to add Spark class names at **Spark-only** raise sites (`velox/functions/sparksql`), with shared helpers returning a failure? A matching Velox issue will follow for the Velox part. 4. Should #13135 and #13639 move onto this contract, or land as they are and migrate later? 5. Is `USER_RAISED_EXCEPTION` as an opt-in interim worth having at all? ## 12. Common questions **If the result is correct whenever the query succeeds, why does the error type matter?** It only matters when the query *fails*. Users, tools and tests decide what to do from the class and SQLSTATE: retry or not, show a "use `try_divide`" hint, or alert. **Why not translate on the driver?** By the time the driver sees "Job aborted", the decision to wrap has already been made (§3, step ⑤). **Does `try_add` / `try_cast` get slower?** No. Inside TRY the helper returns before building any text (§6.3), and a benchmark checks this. **Will Presto change?** No. Shared helpers don't name Spark classes; the Spark caller attaches them (§6.6). **Isn't a typed Velox exception (D) better than text?** The transport is cleaner, but on its own it isn't enough: every raise site still has to name the class and its parameters. That work is the same in C and D, and the contract lets us switch later (§6.7). Reviews welcome, especially on the open questions in §11. Once we agree on a direction, I'll split the work into small PRs. cc @rui-mo @philo-he @zhztheplayer @baibaichen @LuciferYang @felipepessoto @pedrumj2 -- 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]
