Skip to content

feat: route extract and date_part of interval fields through codegen dispatch - #7832

Open
talz-a wants to merge 7 commits into
apache:mainfrom
talz-a:interval-extract-serde
Open

talz-a wants to merge 7 commits into
apache:mainfrom
talz-a:interval-extract-serde

Conversation

@talz-a

@talz-a talz-a commented Dec 2, 2026 •

Copy link
Copy Markdown

Which issue does this PR close?

Closes #6193.

Rationale for this change

As the issue states, Spark lowers extract(field FROM interval) and date_part('field', interval) to one of twelve ExtractIntervalPart subclasses, and since none of them have a serde, a projection that uses one falls back to Spark.

We want these twelve expressions to run through the JVM codegen dispatcher instead.

This also keeps date +/- DAY interval in Comet. Spark rewrites it to DateAdd(date, ExtractANSIIntervalDays(interval)), and DateAdd is already native, so the extractor was the only reason those projections fell back.

What changes are included in this PR?

  • Register the twelve ExtractANSIInterval* and ExtractInterval* expressions as CometCodegenDispatch serdes in datetime.scala and QueryPlanSerde.temporalExpressions. Each one is a single IntervalUtils.getX(child) call, and the classes and result types are the same on every supported Spark version, so no shim is needed.
  • Wrap CometDateAdd in withNullShortCircuit, so a NULL date skips the interval operand as it does in Spark. Without it, an out-of-range CAST(n AS INTERVAL DAY) on a row with a NULL date raises CAST_OVERFLOW in Comet, where Spark returns NULL.
  • Add a note to the extract, date_part and datepart rows in expressions.md.
  • Remove the interval date_part case from explain comet, which used it as an unsupported example.

How are these changes tested?

A new SQL file test, expressions/datetime/extract_interval.sql, checks every extractor with expect_dispatch(...), using extract, date_part and datepart, over Parquet data with negative, NULL and out-of-range values. It covers:

  • year-month, day-time and calendar intervals built from columns
  • literal interval input
  • boundary values
  • narrower ANSI types such as INTERVAL MONTH and INTERVAL HOUR TO SECOND
  • date +/- CAST(n AS INTERVAL DAY) and date +/- INTERVAL '30' DAY for the DateAdd rewrite
  • date +/- (d1 - d2) from the issue, over three date columns with NULLs and a negative difference. The dispatcher compiles SubtractDates into the extractor's kernel, so this does not depend on feat: route date and timestamp interval arithmetic through codegen dispatch #5864.
  • with ANSI on, a NULL date with an out-of-range DAY interval returns NULL for + and - in separate projections, and still raises CAST_OVERFLOW when both appear in one projection, where Spark shares the extractor and evaluates it for every row

#5864 adds + / - notes to expressions.md saying a DAY interval column falls back because ExtractANSIIntervalDays has no serde. Whichever of the two PRs merges second should drop that sentence.

…dispatch

Register serdes for the twelve ExtractANSIInterval* and ExtractInterval*
expressions so they run through the JVM codegen dispatcher instead of
falling back to Spark. This also keeps date +/- DAY interval in Comet,
which Spark rewrites to DateAdd over ExtractANSIIntervalDays.

Closes apache#6193
@talz-a
talz-a marked this pull request as ready for review December 2, 2026 20:23

@comphead comphead 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.

All twelve ExtractIntervalPart subclasses (ExtractANSIInterval{Years,Months,Days,Hours,Minutes,Seconds} and ExtractInterval{...}) are registered, and they match v3.5.8, v4.0.1 and v4.1.1 (same names, same IntervalUtils.getX bodies, DecimalType(8, 6) for seconds). The CometCodegenDispatch objects follow the existing CometMakeDTInterval pattern, so no shim is needed. The fixture covers year-month, day-time and calendar intervals, NULL, negatives and the exact Int and Long boundaries, and it replaces the deleted Scala case. The date +/- DAY interval rewrite (DateAdd(l, ExtractANSIIntervalDays(r)), with UnaryMinus for subtract) is covered. The PR adds twelve generated spark.comet.expression.Extract*Interval*.enabled keys through the enable_expr table, and the Implementation column of expressions.md stays generated, so only the hand-written notes change. I did not run anything. I could not run the cross-PR overlap query because gh was blocked, so I did not check the overlap with #5864 beyond what the PR body says.

@comphead comphead 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 @talz-a, the PR goes into right direction, please check some nits!

@sunchao sunchao 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.

The new interval fixture passed on Spark 4.1.3. I found a correctness regression in date arithmetic when the date is NULL. I reproduced it for both signs and tested a fix in CometDateAdd.

Automated review by Codex.

@talz-a
talz-a requested a review from sunchao December 3, 2026 02:13

@sunchao sunchao 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 for fixing the null-date case. The updated SQL fixture passed on Spark 4.1.3. I compared a7230f82 with d7fd610b using the two rows in test_date_day_overflow. I found four more cases where the base matched Spark and this revision changes whether the query raises. I'd address those before merging. I also verified that the date subtraction example from #6193 already works here.

Automated review by Codex.


object CometExtractANSIIntervalSeconds extends CometCodegenDispatch[ExtractANSIIntervalSeconds]

object CometExtractANSIIntervalYears extends CometCodegenDispatch[ExtractANSIIntervalYears]

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.

Two extractors can now silently skip an ANSI overflow. I reproduced this on test_date_day_overflow with ANSI and subexpression elimination enabled.

SELECT extract(YEAR FROM make_ym_interval(year(d), n * 24)),
       extract(MONTH FROM make_ym_interval(month(d), n * 24))
FROM test_date_day_overflow

Spark computes the shared n * 24 before either null check and raises ARITHMETIC_OVERFLOW. Comet compiles each extractor separately, so both skip the multiplication when d is null. I got (NULL, NULL) and (2026, 0) instead. With subexpression elimination off, both engines return those rows.

This is related to #7480. Could we fall back when separate kernels would skip a shared expression that can throw, and cover both settings?

object CometDateAdd extends CometScalarFunction[DateAdd]("date_add")
object CometDateAdd extends CometScalarFunction[DateAdd]("date_add") {
override def convert(expr: DateAdd, inputs: Seq[Attribute], binding: Boolean): Option[Expr] = {
withNullShortCircuit(expr, super.convert(expr, inputs, binding))

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.

The new guard fixes the single-use cast. It still evaluates too much when Spark shares just part of the expression.

SELECT n + 1, d + CAST(n + 1 AS INTERVAL DAY)
FROM test_date_day_overflow

With ANSI and subexpression elimination on, Spark shares only n + 1. It still skips the cast on the null date and returns (106751993, NULL) and (2, 2024-01-03). canSkipEvaluation finds the shared addition anywhere under the right operand and disables the guard for the entire operand. Comet then raises CAST_OVERFLOW.

Could we keep the unshared cast conditional, or fall back for partial sharing? The existing test where Spark shares the whole extractor should still raise.


object CometMakeDTInterval extends CometCodegenDispatch[MakeDTInterval]

object CometExtractANSIIntervalDays extends CometCodegenDispatch[ExtractANSIIntervalDays]

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.

This also enables projections where the parent evaluates the extractor on rows Spark skips. For example, with ANSI on,

SELECT date_sub(d, extract(DAY FROM CAST(n AS INTERVAL DAY)))
FROM test_date_day_overflow

Spark returns NULL and 2023-12-31. Comet raises CAST_OVERFLOW. Explicit date_sub uses DateSub, so neither of the DateAdd tests covers it. I reproduced the same failure with year(d) + extract(...) and year(d) = extract(...).

Could we guard DateSub too and keep these projections on Spark wherever a native parent can evaluate a throwing extractor on skipped rows? CometMakeDate.unsupportedParentReason has a similar check.

classOf[ExtractANSIIntervalMonths] -> CometExtractANSIIntervalMonths,
classOf[ExtractANSIIntervalSeconds] -> CometExtractANSIIntervalSeconds,
classOf[ExtractANSIIntervalYears] -> CometExtractANSIIntervalYears,
classOf[ExtractIntervalDays] -> CometExtractIntervalDays,

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.

Calendar DAY extraction itself can throw even with ANSI off. With Comet shuffle enabled, AQE off, and the two fixture rows in one Parquet file, I ran

SET spark.sql.ansi.enabled=false;
SELECT n FROM test_date_day_overflow
ORDER BY n, extract(DAY FROM make_interval(0, 0, 0, 2147483647, n))
LIMIT 1

Spark returns 1 because the first keys differ. Comet TopK evaluates both keys and hits integer overflow in IntervalUtils.getDays when it adds the whole days from the hours to Int.MaxValue. Replacing the second key with extract(DAY FROM CAST(n AS INTERVAL DAY)) gives CAST_OVERFLOW instead. With ANSI on, the existing fallback handles both.

Could we include these cases in raisesInAnyMode so the fallback for later sort keys (#7246) applies with ANSI off, and cover them in topk_later_key_ansi.sql?

@github-actions github-actions Bot added enhancement New feature or request area:expressions Expression evaluation labels Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:expressions Expression evaluation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ExtractANSIIntervalDays and the other interval field extractors have no serde, so date + <day interval column> and extract of an interval fall back

3 participants