Skip to content

[SPARK-62149][SQL] Add try_abs and try_negative that return NULL on overflow - #60769

Open
MaxGekk wants to merge 4 commits into
apache:masterfrom
MaxGekk:SPARK-62149-try-abs-negative
Open

MaxGekk wants to merge 4 commits into
apache:masterfrom
MaxGekk:SPARK-62149-try-abs-negative

Conversation

@MaxGekk

@MaxGekk MaxGekk commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

What changes were proposed in this pull request?

This PR adds two SQL functions, try_abs(expr) and try_negative(expr), with the semantics of abs and negative, except that they return NULL instead of raising an overflow error, as try_add, try_subtract and try_multiply do. The result is NULL for:

  • the minimum value of TINYINT, SMALLINT, INT and BIGINT;
  • the minimum value of a YEAR TO MONTH or DAY TO SECOND interval;
  • for try_negative, a legacy CALENDAR INTERVAL with a field at its minimum value (abs does not accept that type).

Like the other try_ arithmetic functions, they return NULL there whatever spark.sql.ansi.enabled is. For every other input they are abs and negative: floating-point and decimal values cannot overflow (Decimal.abs and negation keep the precision), and a string or NULL argument is coerced to DOUBLE as for abs.

Implementation:

  • TryAbs and TryNegative in TryEval.scala are RuntimeReplaceable with InheritAnalysisRules, like TryAdd. Over a type that can overflow, the replacement is AbsOrNull / NegateOrNull; otherwise it is Abs / UnaryMinus.
  • AbsOrNull and NegateOrNull (in arithmetic.scala, next to Abs) extend UnaryArithmeticOrNull. They compare the value with the minimum of its type, and return NULL there, in both the interpreted path and generated code. They are nullable, check their input types, and are NoThrow, since they cannot raise themselves.
  • They do not use TryEval, so an error raised by the argument itself still surfaces: under ANSI mode, try_abs(2147483647 + 1) raises ARITHMETIC_OVERFLOW from the addition. try_add over intervals wraps the expression in TryEval, which also hides such errors. A consequence: under ANSI mode, try_negative('abc') raises CAST_INVALID_INPUT from the implicit cast to DOUBLE, where try_add(1, 'abc') returns NULL.
  • functions.try_abs / functions.try_negative in Scala, and the PySpark (classic and Connect) functions, with docs. The SQL function reference and sql-ref-ansi-compliance.md list both.

Why are the changes needed?

Spark has try_ counterparts for the arithmetic operators that raise an overflow error under ANSI mode (try_add, try_subtract, try_multiply, try_divide, try_mod, try_sum, try_avg), but not for the unary ones. Under ANSI mode, abs(x) and -x raise ARITHMETIC_OVERFLOW for the minimum value of an integral type, for example abs(-2147483648), and the only ways to get NULL instead were to turn ANSI mode off or to write CASE WHEN x = <minimum> THEN NULL ELSE abs(x) END per type.

Does this PR introduce any user-facing change?

Yes, two new SQL functions and the matching Scala and Python APIs:

SELECT try_abs(-1), try_abs(-2147483648), try_negative(-9223372036854775808L);
-- 1    NULL    NULL
SELECT try_negative(INTERVAL '-178956970-8' YEAR TO MONTH);
-- NULL

How was this patch tested?

  • TryEvalSuite: AbsOrNull and NegateOrNull over the minimum, minimum + 1, maximum, -1, 0, 1 and NULL of each integral type and of both ANSI interval types, in the interpreted, mutable-projection and unsafe-projection modes. Also try_negative over calendar intervals with each field at its minimum, the types that cannot overflow, the replacement with ANSI mode on and off, the input type checks, and an argument whose own error is not caught.
  • ExprUtilsSuite: both classes are listed as NoThrow, and they do not raise over the extreme values of each integral type.
  • try_arithmetic.sql (ANSI and non-ANSI golden files): literals and column-read inputs of every integral type, intervals, decimals at DECIMAL(38, 0) extremes, doubles, strings, NULL, an argument that raises, and invalid input types.
  • streaming/try-abs-negative.sql: both functions in a streaming flow.
  • MathFunctionsSuite: the SQL and DataFrame API forms with ANSI mode on and off.
  • PlanGenerationTestSuite / ProtoToParsedPlanTestSuite: new Connect golden files.
  • ExpressionsSchemaSuite (regenerated sql-expression-schema.md), ExpressionInfoSuite (the examples), and the function parity test in DataFrameFunctionsSuite.
  • The PySpark doctests of both functions, in classic mode with ANSI mode on and off.
build/sbt 'catalyst/testOnly *TryEvalSuite *ExprUtilsSuite' \
  'sql/testOnly *MathFunctionsSuite *DataFrameFunctionsSuite *ExpressionInfoSuite *ExpressionsSchemaSuite' \
  'sql/testOnly *SQLQueryTestSuite -- -z try_arithmetic.sql' \
  'sql/testOnly *StreamingSQLQueryTestSuite -- -z try-abs-negative' \
  'connect-client-jvm/testOnly *PlanGenerationTestSuite -- -z try_abs -z try_negative' \
  'connect/testOnly *ProtoToParsedPlanTestSuite -- -z try_abs -z try_negative'

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

Generated-by: Claude Code (Claude Opus 5.5)

MaxGekk and others added 4 commits November 20, 2026 23:40
…verflow

Under ANSI mode, abs(x) and negative(x) raise ARITHMETIC_OVERFLOW for the minimum value of an
integral type, and there was no try_ form for them. try_abs and try_negative return NULL there
instead. With ANSI mode off they behave as abs and negative do, and for the other types,
including intervals, they are abs and negative.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… and streaming

The docs said NULL for any unrepresentable result, but the functions return NULL only for the
minimum value of an integral type under ANSI mode. The expression examples no longer depend on
the ANSI default, which the non-ANSI CI job turns off. Also test DECIMAL(38, 0) extremes, which
cannot overflow, and add a streaming golden test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…r try_ functions

try_abs and try_negative now return NULL for the minimum value of an integral type with ANSI
mode off too, and for the minimum of an ANSI interval, and try_negative for a calendar interval
with a field at its minimum, as try_add, try_subtract and try_multiply return NULL on overflow
in both modes and over intervals. The null-on-overflow expressions check their input types and
are NoThrow. Also test invalid input types, and expect the exact interval overflow error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nd resolve their evaluation once

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MaxGekk

MaxGekk commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

@HyukjinKwon @zhengruifeng @srielau could you take a look when you have a moment? This adds try_abs and try_negative, the missing unary members of the try_ arithmetic family. Like try_add, they return NULL on overflow in both ANSI modes: for the minimum value of an integral type, the minimum of a YEAR TO MONTH or DAY TO SECOND interval, and, for try_negative, a calendar interval with a field at its minimum. Errors of the argument itself still surface. The PR also adds the Scala, PySpark and Connect APIs.

@dongjoon-hyun dongjoon-hyun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you for adding try_abs and try_negative, @MaxGekk. The core overflow logic looks correct to me: the minimum-value checks in both the interpreted and codegen paths, the CalendarInterval field checks, and the nullability. I left a few comments. In short:

  1. STRING input under ANSI mode (TryEval.scala): try_abs('abc') / try_negative('abc') raise CAST_INVALID_INPUT, while try_add(1, 'abc') returns NULL. This is inconsistent with the other try_* functions.
  2. Overflow error hint (sql-ref-ansi-compliance.md): the ANSI overflow errors of abs / negative don't suggest the new functions yet, unlike +, -, and *. A follow-up is fine.
  3. Design question (arithmetic.scala): EvalMode.TRY for Abs / UnaryMinus instead of a parallel *OrNull hierarchy, to avoid duplicating the overflow rule.
  4. nit (arithmetic.scala): share the CalendarInterval overflow check between the interpreted and codegen paths.
  5. Error message (TryEval.scala): sqlExpr shows abs(...) instead of try_abs(...) for invalid input types. The existing try_* functions behave the same, so this is optional.
  6. nit (ExprUtilsSuite): cover the interval types in the NoThrow evaluation checks.
  7. nit (ExprUtilsSuite): reflow the sorted class list.

def this(expr: Expression) = this(expr, expr.dataType match {
case _: IntegralType | _: AnsiIntervalType => AbsOrNull(expr)
// The other types that `abs` accepts cannot overflow.
case _ => Abs(expr)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Under ANSI mode, this fallback makes a STRING argument raise CAST_INVALID_INPUT from the implicit cast to DOUBLE, e.g. SELECT try_negative('abc') in the ANSI golden file. Meanwhile, try_add(1, 'abc') returns NULL because TryAdd wraps non-numeric inputs in TryEval.

I understand from the PR description that avoiding TryEval is intentional so that the argument's own errors (e.g. try_abs(2147483647 + 1)) still surface. However, from the user's perspective, try_abs('abc') failing where try_add(1, 'abc') returns NULL looks inconsistent with the other try_* functions and with the EvalMode.TRY contract ("returning null result on errors").

Could we make the StringType case NULL-on-error as well (e.g., TryEval(Abs(expr)) only for that case), or at least document this difference in the function usage and sql-ref-ansi-compliance.md? The same applies to TryNegative (L116).

- `try_multiply`: identical to the add operator `*`, except that it returns `NULL` result instead of throwing an exception on integral value overflow.
- `try_divide`: identical to the division operator `/`, except that it returns `NULL` result instead of throwing an exception on dividing 0.
- `try_mod`: identical to the remainder operator `%`, except that it returns `NULL` result instead of throwing an exception on dividing 0.
- `try_abs`: identical to the function `abs`, except that it returns `NULL` result instead of throwing an exception on integral or interval value overflow.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Now that try_abs and try_negative exist, shall we suggest them in the ANSI overflow errors of abs, negative, and the unary minus, like +, -, and * suggest try_add, try_subtract, and try_multiply? Currently, MathUtils.negateExact (Byte/Short/Int/Long) and IntervalMathUtils.negateExact pass no suggested function, so SELECT abs(-2147483648) under ANSI mode still shows only the following, the same as the example at L82 of this doc.

[ARITHMETIC_OVERFLOW] integer overflow. If necessary set spark.sql.ansi.enabled to "false" to bypass this error.

Users who hit this error have no way to discover the new functions. It's fine to do this in a follow-up.

* or an ANSI interval, both overflow only on the minimum value of the type. `try_abs` and
* `try_negative` are replaced with a subclass over the types that can overflow.
*/
abstract class UnaryArithmeticOrNull extends UnaryExpression with ExpectsInputTypes {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Design question: instead of a parallel hierarchy (UnaryArithmeticOrNull, AbsOrNull, NegateOrNull), have you considered giving Abs and UnaryMinus an EvalMode with TRY, like Add, Subtract, and Multiply? Then try_abs could be Abs(expr, EvalMode.TRY), as TryAdd uses Add(left, right, EvalMode.TRY).

With the current approach, the "overflow only on the minimum value" rule lives in MathUtils.negateExact, IntervalUtils.negateExact, and here (in both the interpreted and codegen paths), and the type dispatch in TryAbs / TryNegative repeats it once more. If the supported types or overflow rules of abs / negative change later, all of them need to be kept in sync manually. I understand that changing failOnError: Boolean to EvalMode is a bigger change, so I'm fine with deferring it if you prefer.

override protected def nonNullEvaluator: Any => Any = dataType match {
case CalendarIntervalType => input =>
val v = input.asInstanceOf[CalendarInterval]
if (v.months == Int.MinValue || v.days == Int.MinValue || v.microseconds == Long.MinValue) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: This overflow condition is duplicated in the codegen string below (L329-330), and it also mirrors IntervalUtils.negateExact. How about adding a helper like IntervalUtils.negateOrNull(interval: CalendarInterval): CalendarInterval, which returns null on overflow, and calling it from both the interpreted and codegen paths? Then the two paths cannot drift apart.

""",
since = "4.5.0",
group = "math_funcs")
case class TryAbs(expr: Expression, replacement: Expression)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

For an invalid input type, the type check fails on the replacement, so sqlExpr shows a function that the user didn't write. For example, the golden file has "sqlExpr" : "\"abs(true)\"" for try_abs(true) and "sqlExpr" : "\"abs(make_interval(0, 1, 0, 0, 0, 0, 0.000000))\"" for try_abs(make_interval(0, 1)). Only fragment shows try_abs(...).

I know the existing try_* functions (e.g. try_add, try_reflect) behave the same way, so this is not a blocker. Just mentioning it in case you want to report it as try_abs(...) / try_negative(...).

}
// The null-on-overflow forms of try_abs and try_negative.
for ((t, values) <- Seq(longs, ints, shorts, bytes)) {
evalEach(t, values)(AbsOrNull(_))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: AbsOrNull and NegateOrNull are declared NoThrow over all of their input types, but these checks cover only the integral types. TryEvalSuite already checks the interval minimums functionally, but for completeness of the NoThrow checks here, could we also add both ANSI interval types (like L289-291 do for UnaryMinus / Abs) and CalendarIntervalType for NegateOrNull? Then a later change that makes an interval path throw would fail this suite too.

Comment on lines +738 to 740
"NullIf",
"OctetLength", "Or", "Quarter", "Second", "SecondWithFraction", "Size", "StartsWith",
"Substring", "WeekDay", "WeekOfYear", "Year", "YearOfWeek"))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: "NullIf", is left alone on this line. How about reflowing the remaining lines?

Suggested change
"NullIf",
"OctetLength", "Or", "Quarter", "Second", "SecondWithFraction", "Size", "StartsWith",
"Substring", "WeekDay", "WeekOfYear", "Year", "YearOfWeek"))
"NullIf", "OctetLength", "Or", "Quarter", "Second", "SecondWithFraction", "Size",
"StartsWith", "Substring", "WeekDay", "WeekOfYear", "Year", "YearOfWeek"))

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants