← Back to Pull requests

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

Closed
unknown closed this pull request without merging on Nov 29, 2026 09:45 UTC
View on GitHub
unknown unknown commented on Nov 05, 2026 16:34 UTC
Author

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)

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: stevomitric Review duration: 34150m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #60134"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%
    Repository