[SPARK-60910][SQL] Fail on overflow in datediff instead of wrapping around #60134
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
stevomitric
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)