Skip to content

[SPARK-60910][SQL] Fail on overflow in datediff instead of wrapping around - #60134

Open
SEPURI-SAI-KRISHNA wants to merge 10 commits into
apache:masterfrom
SEPURI-SAI-KRISHNA:datediff-overflow
Open

SEPURI-SAI-KRISHNA wants to merge 10 commits into
apache:masterfrom
SEPURI-SAI-KRISHNA:datediff-overflow

Conversation

@SEPURI-SAI-KRISHNA

@SEPURI-SAI-KRISHNA SEPURI-SAI-KRISHNA commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

What changes were proposed in this pull request?

This PR makes datediff / date_diff with two date arguments (DateDiff) fail with DATETIME_OVERFLOW when the number of days between the dates does not fit in an Int, instead of silently wrapping around. It adds DateTimeUtils.daysBetween, which uses Math.subtractExact, and uses it in both the interpreted and the generated code.

It also makes subtracting a date from a date (SubtractDates, for example d1 - d2) raise the same DATETIME_OVERFLOW error instead of a raw java.lang.ArithmeticException when the difference does not fit in the day-time interval result. The new DateTimeUtils.subtractDatesToMicros subtracts the day counts as Longs, so a single Math.multiplyExact detects every overflow.

Both errors carry the query context of the expression, so they show which datediff or d1 - d2 overflowed. DateDiff and SubtractDates mix in a new DateArithmeticQueryContext, a SupportQueryContext whose query context is that of the expression (SubtractDates has none with spark.sql.legacy.interval.enabled, where it cannot overflow). With ANSI mode off, d1 - d2 is first resolved into a Subtract, which has no query context as it cannot fail. Since #60285, SupportQueryContext.copyTagsFrom does not copy that missing context onto the SubtractDates that 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, whatever spark.sql.legacy.timeParserPolicy is. Under LEGACY, 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 raw java.lang.ArithmeticException instead. The next_day, last_day and trunc overflow errors of SPARK-60929 use the helper too: trunc overflows only at the minimum DATE, so under LEGACY, for example, trunc(date_from_unix_date(-2147483648), 'QUARTER') failed the same way.

Why are the changes needed?

DateDiff subtracts the two day counts as Ints, so the result wraps around for dates far apart, with ANSI mode on or off:

SELECT datediff(date_from_unix_date(2147483647), date_from_unix_date(-1));
-- -2147483648, should be 2147483648

SELECT datediff(date_from_unix_date(2147483647), date_from_unix_date(-2147483648));
-- -1, should be 4294967295

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 with java.lang.ArithmeticException: integer overflow (or long 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_diff now fail instead of returning a wrapped value, regardless of spark.sql.ansi.enabled:

org.apache.spark.SparkArithmeticException: [DATETIME_OVERFLOW] Datetime operation overflow: subtract DATE '1969-12-31' from DATE '+5881580-07-11'. SQLSTATE: 22008
== SQL (line 1, position 8) ==
SELECT datediff(date_from_unix_date(2147483647), date_from_unix_date(-1))
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Subtracting a date from a date fails with the same error instead of java.lang.ArithmeticException in that case, and try_subtract on dates still returns NULL. 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 wrapped datediff result; 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) or NULL (try_subtract(unix_date(end), unix_date(start))). The datediff usage says that it fails with DATETIME_OVERFLOW in that case.

Under spark.sql.legacy.timeParserPolicy=LEGACY, the dates in a DATETIME_OVERFLOW message of datediff, date subtraction, next_day, last_day and trunc are now formatted as under the other policies, for example DATE '+5881580-07-11' instead of DATE '5881580-07-11', and a date near the minimum DATE no longer makes trunc fail with java.lang.ArithmeticException instead of DATETIME_OVERFLOW.

timestampdiff and months_between on 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?

  • New tests in DateExpressionsSuite: datediff overflow in both directions, the largest and smallest differences that still fit, and the interpreted vs codegen consistency check for DateDiff; SubtractDates overflow just past the largest day-time interval (106751991 days) and far past it, and the largest differences that still fit; the datediff overflow at both ends of the DATE range, and the date subtraction and trunc overflows at the minimum DATE, under each spark.sql.legacy.timeParserPolicy (fails without the toSQLDate change with java.lang.ArithmeticException: integer overflow from RebaseDateTime.localRebaseGregorianToJulianDays under LEGACY).
  • New queries at the end of date.sql (also imported by nonansi/date.sql and datetime-legacy.sql), golden files regenerated; two of them (datediff and -) overflow at the minimum DATE, which datetime-legacy.sql runs under LEGACY. Without this change, the datediff cases return the wrapped values -2147483648 and 2147483647, and the subtraction case fails with java.lang.ArithmeticException: integer overflow (checked on master).
  • Updated the date subtraction overflow check in ColumnExpressionSuite (SPARK-34896), which expected the raw ArithmeticException, to expect DATETIME_OVERFLOW with the DataFrame query context.
  • A new DateFunctionsSuite test that the error has the query context of the overflowing expression, for datediff and e - s in SQL and datediff in the DataFrame API, with ANSI mode on and off, and that the replacements in the migration guide give the previous result and NULL. The golden files show the query context of each overflow in date.sql, nonansi/date.sql and datetime-legacy.sql.
  • Ran DateExpressionsSuite, DateTimeUtilsSuite, DateFunctionsSuite, ColumnExpressionSuite, and the date, datetime-legacy, timestamp and interval tests in SQLQueryTestSuite.

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

Generated-by: Claude Code (Claude Opus 5.5)

@stevomitric stevomitric 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 @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

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.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

…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])

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.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 = {

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.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 MaxGekk 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.

Thanks, the context and the note look good. A few nits:

  • branch-4.4 has been cut, so unless this is backported, the note should say "Since Spark 4.5", in a 4.4 to 4.5 section.
  • The DateArithmeticQueryContext trait is the same as in #59135, so the second PR to merge will conflict. Its copyTagsFrom override becomes unnecessary with #60285.
  • subtractDatesOverflowError would fit next to the other DATE overflow builders (nextDayOverflowError, truncDateOverflowError), and could return SparkArithmeticException as they do.
  • The usage of datediff could mention that it fails with DATETIME_OVERFLOW when the number of days does not fit in an INT, in every mode.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Contributor Author

@MaxGekk thanks, updated:

@MaxGekk

MaxGekk commented Nov 23, 2026

Copy link
Copy Markdown
Member

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 datediff usage mentions the new error.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Contributor Author

@MaxGekk thanks. #60285 is in, so I merged master and dropped the copyTagsFrom override, as in #59135.

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.

3 participants