Repository navigation
[SPARK-60910][SQL] Fail on overflow in datediff instead of wrapping around - #60134
SEPURI-SAI-KRISHNA wants to merge 10 commits into
Conversation
stevomitric
left a comment
There was a problem hiding this comment.
Thanks @SEPURI-SAI-KRISHNA for the followup!
Left one commend, could you please check it out?
| @@ -3779,11 +3779,12 @@ case class DateDiff(endDate: Expression, startDate: Expression) | |||
| override def dataType: DataType = IntegerType | |||
There was a problem hiding this comment.
Under spark.sql.legacy.timeParserPolicy=LEGACY, toSQLValue(..., DateType) goes through the legacy formatter, which rebases Gregorian to Julian days. For dates within ~44k days of Int.MinValue that overflows, so building this error throws a raw ArithmeticException (instead of DATETIME_OVERFLOW) - could you check this please?
There was a problem hiding this comment.
Thanks @stevomitric, good catch, confirmed. Under LEGACY, toSQLValue(_, DateType) goes through LegacyDateFormatter.format, and RebaseDateTime.localRebaseGregorianToJulianDays throws ArithmeticException: integer overflow from Math.toIntExact for the dates within about 44,500 days of the minimum DATE. So datediff(date_from_unix_date(-2147483648), date_from_unix_date(1)) failed with a raw ArithmeticException, and so did date_from_unix_date(-2147483648) - date_from_unix_date(0), which reaches the same error. The trunc overflow error from SPARK-60929 has the same problem, since trunc overflows only at the minimum DATE, e.g. trunc(date_from_unix_date(-2147483648), 'QUARTER') under LEGACY.
Fixed in 49e0d76: a private QueryExecutionErrors.toSQLDate formats with DefaultDateFormatter, in the proleptic Gregorian calendar of DATE values, whatever the policy. subtractDatesOverflowError and the next_day / last_day / trunc overflow errors use it. The text is unchanged under CORRECTED and EXCEPTION; under LEGACY the maximum DATE now prints as +5881580-07-11, as it does under the other policies.
Tests: a new DateExpressionsSuite case runs the datediff overflow at both ends of the DATE range, and the date subtraction and trunc overflows at the minimum DATE, under all three policies (without the change it fails under LEGACY with the raw ArithmeticException). date.sql has two new queries that overflow at the minimum DATE, and datetime-legacy.sql runs them under LEGACY. I also merged master to resolve the migration-guide conflict with SPARK-60929.
# Conflicts: # docs/sql-migration-guide.md
…tter Under spark.sql.legacy.timeParserPolicy=LEGACY, toSQLValue(_, DateType) formats with the legacy formatter, whose rebasing to the Julian calendar overflows for the dates within about 44,500 days of the minimum DATE, so building the error threw a raw java.lang.ArithmeticException. Format the dates of the datediff, date subtraction, next_day, last_day and trunc overflow errors in the proleptic Gregorian calendar whatever the policy.
|
|
||
| override def nullSafeEval(end: Any, start: Any): Any = { | ||
| end.asInstanceOf[Int] - start.asInstanceOf[Int] | ||
| DateTimeUtils.daysBetween(end.asInstanceOf[Int], start.asInstanceOf[Int]) |
There was a problem hiding this comment.
With spark.sql.ansi.enabled=false, datediff/date_diff now fail with DATETIME_OVERFLOW instead of wrapping, and there is neither a legacy flag nor a try_ form, so a non-ANSI user who hits this can't get NULL back. Could this have a spark.sql.legacy.* flag, or could the migration note say how to get the old result?
There was a problem hiding this comment.
I didn't add a flag. The old result was a wrong day count, it only happens for dates about 5.8 million years apart, and both behaviors are easy to get without one:
- old result:
unix_date(end) - unix_date(start)with ANSI off NULL:try_subtract(unix_date(end), unix_date(start))
The migration note says this, and the test checks both. Happy to add a spark.sql.legacy.* flag if you'd prefer.
| summary = "") | ||
| } | ||
|
|
||
| def subtractDatesOverflowError(endDay: Int, startDay: Int): ArithmeticException = { |
There was a problem hiding this comment.
As in #59135: subtractDatesOverflowError passes context = Array.empty, and neither DateDiff nor SubtractDates supplies one, so the error doesn't show which datediff or d1 - d2 overflowed. Could they extend SupportQueryContext and pass getContextOrNull() through daysBetween/subtractDatesToMicros?
There was a problem hiding this comment.
Done. DateDiff and SubtractDates now pass their query context to the error, in both eval and codegen. SubtractDates has no context under spark.sql.legacy.interval.enabled, where it can't overflow.
They use the same DateArithmeticQueryContext trait as #59135, so the empty context from the ANSI-off Subtract isn't copied over. The new test in DateFunctionsSuite checks datediff and e - s in SQL and datediff in the DataFrame API, with ANSI on and off. The golden files show the context too.
MaxGekk
left a comment
There was a problem hiding this comment.
Thanks, the context and the note look good. A few nits:
branch-4.4has been cut, so unless this is backported, the note should say "Since Spark 4.5", in a 4.4 to 4.5 section.- The
DateArithmeticQueryContexttrait is the same as in #59135, so the second PR to merge will conflict. ItscopyTagsFromoverride becomes unnecessary with #60285. subtractDatesOverflowErrorwould fit next to the other DATE overflow builders (nextDayOverflowError,truncDateOverflowError), and could returnSparkArithmeticExceptionas they do.- The
usageofdatediffcould mention that it fails withDATETIME_OVERFLOWwhen the number of days does not fit in an INT, in every mode.
|
@MaxGekk thanks, updated:
|
|
LGTM. Thank you for addressing the comments, @SEPURI-SAI-KRISHNA: the note is under 4.4 to 4.5, the error builder sits with the other DATE overflow builders, and the |
… SPARK-61352 is in
# Conflicts: # docs/sql-migration-guide.md
What changes were proposed in this pull request?
This PR makes
datediff/date_diffwith two date arguments (DateDiff) fail withDATETIME_OVERFLOWwhen the number of days between the dates does not fit in anInt, instead of silently wrapping around. It addsDateTimeUtils.daysBetween, which usesMath.subtractExact, and uses it in both the interpreted and the generated code.It also makes subtracting a date from a date (
SubtractDates, for exampled1 - d2) raise the sameDATETIME_OVERFLOWerror instead of a rawjava.lang.ArithmeticExceptionwhen the difference does not fit in the day-time interval result. The newDateTimeUtils.subtractDatesToMicrossubtracts the day counts asLongs, so a singleMath.multiplyExactdetects every overflow.Both errors carry the query context of the expression, so they show which
datedifford1 - d2overflowed.DateDiffandSubtractDatesmix in a newDateArithmeticQueryContext, aSupportQueryContextwhose query context is that of the expression (SubtractDateshas none withspark.sql.legacy.interval.enabled, where it cannot overflow). With ANSI mode off,d1 - d2is first resolved into aSubtract, which has no query context as it cannot fail. Since #60285,SupportQueryContext.copyTagsFromdoes not copy that missing context onto theSubtractDatesthat replaces it, so it keeps its own. The trait is the same as in #59135.The error message formats its dates with the new
QueryExecutionErrors.toSQLDate, in the proleptic Gregorian calendar of DATE values, whateverspark.sql.legacy.timeParserPolicyis. UnderLEGACY,toSQLValue(_, DateType)uses the legacy formatter, whose rebasing to the Julian calendar overflows for the dates within about 44,500 days of the minimum DATE, so building the error would throw a rawjava.lang.ArithmeticExceptioninstead. Thenext_day,last_dayandtruncoverflow errors of SPARK-60929 use the helper too:truncoverflows only at the minimum DATE, so underLEGACY, for example,trunc(date_from_unix_date(-2147483648), 'QUARTER')failed the same way.Why are the changes needed?
DateDiffsubtracts the two day counts asInts, so the result wraps around for dates far apart, with ANSI mode on or off:This is the same class of bug as SPARK-59859 (
date_add/date_sub), and was raised in the review of #59135. Subtracting the same dates (d1 - d2) already fails, but withjava.lang.ArithmeticException: integer overflow(orlong overflow) without an error class.Does this PR introduce any user-facing change?
Yes. When the number of days between the two dates does not fit in an
Int,datediff/date_diffnow fail instead of returning a wrapped value, regardless ofspark.sql.ansi.enabled:Subtracting a date from a date fails with the same error instead of
java.lang.ArithmeticExceptionin that case, andtry_subtracton dates still returnsNULL. Results that fit are unchanged; for dates between 0001-01-01 and 9999-12-31 the difference always fits. There is no configuration to restore the wrappeddatediffresult; the SQL migration guide (4.4 to 4.5) documents the change and how to get the previous result (unix_date(end) - unix_date(start)with ANSI mode off) orNULL(try_subtract(unix_date(end), unix_date(start))). Thedatediffusage says that it fails withDATETIME_OVERFLOWin that case.Under
spark.sql.legacy.timeParserPolicy=LEGACY, the dates in aDATETIME_OVERFLOWmessage ofdatediff, date subtraction,next_day,last_dayandtruncare now formatted as under the other policies, for exampleDATE '+5881580-07-11'instead ofDATE '5881580-07-11', and a date near the minimum DATE no longer makestruncfail withjava.lang.ArithmeticExceptioninstead ofDATETIME_OVERFLOW.timestampdiffandmonths_betweenon such dates are not changed: they cast the dates to timestamps first, and that cast fails for dates outside the timestamp range.How was this patch tested?
DateExpressionsSuite:datediffoverflow in both directions, the largest and smallest differences that still fit, and the interpreted vs codegen consistency check forDateDiff;SubtractDatesoverflow just past the largest day-time interval (106751991 days) and far past it, and the largest differences that still fit; thedatediffoverflow at both ends of the DATE range, and the date subtraction andtruncoverflows at the minimum DATE, under eachspark.sql.legacy.timeParserPolicy(fails without thetoSQLDatechange withjava.lang.ArithmeticException: integer overflowfromRebaseDateTime.localRebaseGregorianToJulianDaysunderLEGACY).date.sql(also imported bynonansi/date.sqlanddatetime-legacy.sql), golden files regenerated; two of them (datediffand-) overflow at the minimum DATE, whichdatetime-legacy.sqlruns underLEGACY. Without this change, thedatediffcases return the wrapped values-2147483648and2147483647, and the subtraction case fails withjava.lang.ArithmeticException: integer overflow(checked on master).ColumnExpressionSuite(SPARK-34896), which expected the rawArithmeticException, to expectDATETIME_OVERFLOWwith the DataFrame query context.DateFunctionsSuitetest that the error has the query context of the overflowing expression, fordatediffande - sin SQL anddatediffin the DataFrame API, with ANSI mode on and off, and that the replacements in the migration guide give the previous result andNULL. The golden files show the query context of each overflow indate.sql,nonansi/date.sqlanddatetime-legacy.sql.DateExpressionsSuite,DateTimeUtilsSuite,DateFunctionsSuite,ColumnExpressionSuite, and the date,datetime-legacy, timestamp and interval tests inSQLQueryTestSuite.Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)