Skip to content

[SPARK-61352][SQL] Keep the query context of interval errors after serialization and rewrites - #60285

Closed
MaxGekk wants to merge 11 commits into
apache:masterfrom
MaxGekk:SPARK-61352-interval-divide-context
Closed

MaxGekk wants to merge 11 commits into
apache:masterfrom
MaxGekk:SPARK-61352-interval-divide-context

Conversation

@MaxGekk

@MaxGekk MaxGekk commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

What changes were proposed in this pull request?

DivideYMInterval and DivideDTInterval share the IntervalDivide trait. Both build the context for their errors (INTERVAL_ARITHMETIC_OVERFLOW.WITH_SUGGESTION, INTERVAL_DIVIDED_BY_ZERO) from origin.context, read at evaluation time in the interpreted path and at code-generation time in doGenCode. This PR makes the division keep its context the way the other arithmetic expressions do:

  • IntervalDivide now mixes in SupportQueryContext, with initQueryContext() = Some(origin.context). The division raises in every mode, so the context is set unconditionally rather than only under ANSI as in Divide.

  • The interpreted evalFunc of both classes calls getContextOrNull(), and doGenCode calls getContextOrNullCode(ctx), in place of origin.context.

  • SupportQueryContext.copyTagsFrom, shared by every expression with a query context, now copies the context of the node it replaces only when that node has one that comes from an origin (SupportQueryContext.hasOrigin: a SQL context with a text and a start index, or any other context such as a DataFrameQueryContext). Until now it also copied None, and a context built from an empty Origin. TreeNode.transformDown/transformUp call afterRule.copyTagsFrom(this) whenever a rule replaces a node, and the replaced node can have no context: the non-ANSI Divide that the analyzer (BinaryArithmeticWithDatetimeResolver) turns into DivideYMInterval / DivideDTInterval has a queryContext of None, and so does a non-ANSI cast that SimplifyCasts replaces with make_ym_interval(...). Copying it left the division or make_*_interval, which raise in every mode, with no context. Today the division still has one, because it reads origin.context; once it reads the field, copying None alone would make select interval 2147483647 month / 0.5 in nonansi/interval.sql lose it.

    The copy still does what SPARK-39166 added it for. On an executor the deserialized expression has an empty origin, and a transform there (BindReferences while a projection is built) rebuilds the node, which then takes the serialized context. A replaced node with a context still gives it to its replacement, so the other ANSI expressions, the DataFrame API and the body of a SQL function keep their contexts as before. Under ANSI, SimplifyCasts dropping CAST(<ym> / -1 AS INTERVAL YEAR TO MONTH) now leaves the division with the cast's context too, as ANSI Add gets under a same-type cast. So does a same-type try_cast in every mode, since Cast.ansiEnabled holds for EvalMode.TRY unless it casts a string to a fractional or datetime type, so an interval-to-interval try_cast has a context even with spark.sql.ansi.enabled=false. Before, the division read origin.context, so with whole-stage codegen it reported its own fragment there.

    Effect on other expressions: only a SupportQueryContext expression with a context of its own that a rule returns in place of a node without one now keeps its context instead of losing it. Such a node is a non-ANSI or try_* form, or one built outside an origin, whose replacement has a context in that mode, such as the interval expressions here. Everything else behaves as before.

  • Same pattern in two siblings: the interpreted paths of MakeYMInterval and MakeDTInterval passed origin.context, although both classes are already SupportQueryContext and their generated code already uses the field. Both now call getContextOrNull().

Not fixed here: copyTagsFrom sets the context of the expression a rule returns in place, and that instance can be shared with a temp view or a parent Dataset, so a division shared that way can report the context of another query that removed a cast over it. This predates the PR for the other SupportQueryContext expressions, such as ANSI Add, and is tracked in SPARK-61467.

Why are the changes needed?

TreeNode does not implement java.io.Serializable, so Java serialization skips its fields. When an expression is deserialized, TreeNode's constructor runs again and sets origin from CurrentOrigin.get, which is empty on an executor. SupportQueryContext exists for this reason (SPARK-39166): its context is a field of the concrete, serializable expression, so it survives the trip to the executor.

The interval divisions never used it. Whole-stage codegen hides the problem, because it generates code on the driver and puts the context into the references array. Any projection built on the executor from the deserialized expression, though, raises the error with an empty context and no == SQL == block. That includes ProjectExec and the other operators when spark.sql.codegen.wholeStage=false, and interpreted projections. For example:

SET spark.sql.ansi.enabled=true;
SET spark.sql.codegen.wholeStage=false;
SELECT CAST(CAST(id - 2147483648 AS INT) AS INTERVAL MONTH) / -1 FROM range(1);

raises [INTERVAL_ARITHMETIC_OVERFLOW.WITH_SUGGESTION] ... SQLSTATE: 22015 with a query context whose fragment is empty and whose start and stop are -1. With whole-stage codegen on, the same query reports the fragment and the caret. CAST(id + 1 AS INTERVAL DAY) / CAST(id AS INT) gives INTERVAL_DIVIDED_BY_ZERO with the same gap. make_ym_interval / make_dt_interval overflows lose the context the same way, but only in interpreted evaluation, since their generated code already used the field. SPARK-60746 made both evaluation paths raise the same condition with a context. This PR closes the remaining gap, where that context is lost once the expression is serialized. The gap is older than SPARK-60746: released versions read origin.context in these classes too.

The gap was found while comparing errors from a columnar engine's fallback projections, which are built on the executor, against Spark's own whole-stage code.

A grep for origin.context across the non-test sources under sql/ finds no other evaluation-time readers. The remaining hits are analysis-time error builders that run on the driver. SPARK-61196 (open) plans to pass a context to the overflow errors of interval add, subtract and negate. It should take it from a SupportQueryContext field as here, not from origin.context, or it will have the same gap.

Does this PR introduce any user-facing change?

Yes. Interval division by a number now reports its SQL query context (the == SQL == block, and the fragment and position in the error's queryContext) when it overflows or divides by zero in a projection built on the executor, for example with spark.sql.codegen.wholeStage=false. Before, those errors had an empty context there. make_ym_interval and make_dt_interval already kept their context in generated code; they now keep it in interpreted evaluation too (the codegen fallback, or spark.sql.codegen.factoryMode=NO_CODEGEN). In non-ANSI mode, an interval division or make_ym_interval / make_dt_interval under a cast to its own type, which SimplifyCasts removes, keeps a context instead of losing it. Under ANSI, an interval division under such a cast now reports the whole CAST(...) as its fragment, as the other ANSI arithmetic does, where before, with whole-stage codegen, it reported the division. The same holds for a same-type try_cast in either mode: the query still fails, since try_cast does not catch an error of its child, and the fragment is the whole try_cast(...). The error condition, SQLSTATE and message parameters do not change.

How was this patch tested?

New tests:

  • IntervalExpressionsSuite, "SPARK-61352: an interval error keeps its query context": builds each expression under withOrigin and evaluates it outside, so the serialization round trip in ExpressionEvalHelper cannot restore the origin from CurrentOrigin. It checks for the == SQL (line 1, position 8) == block in the interpreted, mutable-projection and unsafe-projection modes. Cases: year-month MinValue / -1 (integral, double and decimal), year-month / 0, day-time MinValue / -1 (long, decimal and double), day-time / 0, so that each interpreted division branch is reached, make_ym_interval(2147483647, 0), make_dt_interval(2147483647). Each case is checked in three forms: as built; after SimplifyCasts, run on a one-column Project, removes a same-type Cast around it: with an ANSI or a TRY cast, whose context the expression takes, with a non-ANSI one, which has none, and with an ANSI cast built outside withOrigin, whose context has no origin, so the expression keeps its own in the last two; and after a makeCopy of a deserialized copy, which rebuilds the node with an empty origin as a transform on an executor does. Each form is built from a fresh instance, since copyTagsFrom changes the instance a rule returns.
  • QueryExecutionAnsiErrorsSuite, "SPARK-61352: an interval division error keeps its query context": runs CAST(CAST(id - 2147483648 AS INT) AS INTERVAL MONTH) / -1 and CAST(id + 1 AS INTERVAL DAY) / CAST(id AS INT) end to end, each bare and inside a CAST and a try_cast to its own type (INTERVAL YEAR TO MONTH, INTERVAL DAY TO SECOND), with whole-stage codegen on and off, from one case table, and checks the condition, parameters and the ExpectedContext fragment: the division, or the whole CAST(...) / try_cast(...), whose context the division takes. It also runs spark.range(1).select(expr("CAST(id + 1 AS INTERVAL DAY)") / $"id".cast("int")) in both modes and checks the DataFrameQueryContext: fragment div and the call site. The operands read a column, so they are not constant-folded on the driver.
  • QueryExecutionErrorsSuite, "SPARK-61352: an interval error keeps its query context in non-ANSI mode": the same two divisions plus make_ym_interval(CAST(id AS INT) + 178956971, 0) and make_dt_interval(CAST(id AS INT) + 106751992), bare and inside a CAST to their own type, whose context they keep, and inside a try_cast, whose context they take, under spark.sql.ansi.enabled=false, with whole-stage codegen on and off.

With copyTagsFrom copying None again, the unit test fails on the non-ANSI cast form: the expression under the cast reports no context. Without the hasOrigin check, it fails on the ANSI cast built outside withOrigin. The two suites share the queries and the expected-context helper through IntervalErrorContextTestUtils.

Existing suites pass: IntervalExpressionsSuite, ArithmeticExpressionSuite, DecimalExpressionSuite, SimplifyCastsSuite, CastWithAnsiOnSuite, CastWithAnsiOffSuite, TryCastSuite, QueryExecutionErrorsSuite, QueryExecutionAnsiErrorsSuite, the "Query context" tests of SQLQuerySuite (SPARK-39166 and its follow-ups, which raise from a projection built on the executor), and the whole SQLQueryTestSuite with no golden file changes. Its one failure locally, udtf/udtf.sql - Python UDTFs query #29, is the local Python's ValueError wording for list.index (list.index(x): x not in list against the expected 'input' is not in list), unrelated to this change. catalyst/scalastyle, catalyst/Test/scalastyle and sql/Test/scalastyle pass.

build/sbt 'catalyst/testOnly *IntervalExpressionsSuite *ArithmeticExpressionSuite *DecimalExpressionSuite *SimplifyCastsSuite *CastWithAnsiOnSuite *CastWithAnsiOffSuite *TryCastSuite' \
  'sql/testOnly *QueryExecutionErrorsSuite *QueryExecutionAnsiErrorsSuite' \
  'sql/testOnly org.apache.spark.sql.SQLQuerySuite -- -z "Query context"' \
  'sql/testOnly org.apache.spark.sql.SQLQueryTestSuite'

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

Generated-by: Claude Code (Opus 5.5)

t and others added 2 commits November 10, 2026 07:49
… after the expression is serialized

`DivideYMInterval` and `DivideDTInterval` read `origin.context` when they evaluate or generate
code. `TreeNode.origin` is not serialized, so a copy of the expression deserialized on an
executor, where an interpreted or a non-whole-stage projection is built, raises
INTERVAL_ARITHMETIC_OVERFLOW and INTERVAL_DIVIDED_BY_ZERO without a query context.

Make the shared `IntervalDivide` trait a `SupportQueryContext`, whose context is a field of the
expression and is serialized, and use it in both paths. The division raises in every mode, so it
keeps its own context when a rule copies the empty context of the non-ANSI `Divide` it replaces.
The interpreted paths of `MakeYMInterval` and `MakeDTInterval`, which are already
`SupportQueryContext`, had the same `origin.context` read and now use their field too.

Generated-by: Claude Code (Opus 5.5)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MaxGekk MaxGekk changed the title [SPARK-61352][SQL] Keep the query context of interval division errors after the expression is serialized [SPARK-61352][SQL] Keep an expression's own query context through serialization and rewrites Nov 10, 2026
`SupportQueryContext.copyTagsFrom` always overwrote the expression's context with the
context of the node it replaces. When a rule returns an existing expression in place of a
node, the expression that raises then reports the wrong context: under ANSI,
`SimplifyCasts` replaces `CAST(<ym> / -1 AS INTERVAL YEAR TO MONTH)` with the division,
which took the cast's fragment, and a non-ANSI cast replaced by `make_ym_interval(...)` left
it with none.

Copy the other node's context only when this expression has none of its own: `None`, or a
`SQLQueryContext` regenerated from an empty `Origin`, which is not valid. That keeps what
SPARK-39166 added the copy for: a transform of a deserialized expression on an executor
rebuilds the node with an empty `origin`, and the rebuilt node still takes the serialized
context. A node a rule builds on the driver gets the replaced node's origin from
`CurrentOrigin`, so its own context is the same one. This mirrors `TreeNode.copyTagsFrom`,
which copies tags only to a node without tags.

The local override in `IntervalDivide` is no longer needed and is removed, as is the
`with Serializable` of the two divisions, which `SupportQueryContext` already extends.

The tests cover a same-type cast replaced by each expression, under an ANSI and a non-ANSI
cast, and a rebuild of a deserialized copy. The non-ANSI end-to-end case moves to
`QueryExecutionErrorsSuite`, and the test names get the ticket number.

Generated-by: Claude Code (Opus 5.5)
MaxGekk pushed a commit to MaxGekk/spark that referenced this pull request Nov 10, 2026
Section 10 records the owner's decision of 10 November 2026: the context
is restored upstream by SPARK-61352 (apache#60285), and row 414 has
one step left, fusing ym / -1 and dt / -1 after the sync that brings it.
Section 9 also names the interpreted path of make_ym_interval and
make_dt_interval, and its VarkaColumnarToRowExec citations are corrected.
The defect live on master is a new debt register entry owned by
SPARK-61352. The decline test now covers SMALLINT and TINYINT -1 too.

Generated-by: Claude Code (Opus 5.5)
MaxGekk added a commit to vecbricks/varka that referenced this pull request Nov 10, 2026
…text (#1454)

### What changes were proposed in this pull request?

This PR finds out why Varka's fused `ym / -1` raised a different error from Spark, and keeps `-1` declined, with the real reason recorded, until the upstream fix arrives.

`ym / -1` is a year-month interval divided by minus one. Spark raises `INTERVAL_ARITHMETIC_OVERFLOW.WITH_SUGGESTION` on the one month count whose negation overflows, `Int.MinValue`. Varka could compute it as a checked negation, the `IntNeg` node `-ym` already uses: a lane holding `Int.MinValue` declines the batch, and Varka's row fallback evaluates Spark's own expression for that batch, so Spark's error is the one raised. An earlier attempt built this and reverted it, because the fallback's error had no `== SQL ==` context block where Spark's had one, and nobody found out why.

This PR rebuilds that arm on a branch and prints both engines' errors and the stack of the raise. Since the apache sync, both of Spark's evaluation paths raise one condition with the context (SPARK-60746). Both engines raise the same condition, SQL state and parameters. Varka's raise comes from `IntervalMathUtils.divide` inside the fallback's `SpecificUnsafeProjection`, as designed, but its query context has every field empty.

The cause is serialization. `TreeNode` does not implement `java.io.Serializable`. When a plan is deserialized on an executor, Java serialization skips `TreeNode`'s fields and runs its constructor again, so `origin` comes back as `CurrentOrigin.get`, which is empty there. A round trip through `Utils.serialize`/`deserialize` shows it: a `DivideYMInterval` built with an origin comes back with an empty one. Spark's whole-stage code keeps the context because it is generated on the driver: `errCtx` goes into the references array, and a `QueryContext` serializes. Varka's fallback and merge projections are compiled inside the evaluator, on the executor, from the deserialized projection list. Most expressions are not affected, because they hold their context in a `SupportQueryContext` field of the concrete class, and that field serializes. `DivideYMInterval` and `DivideDTInterval` read `origin.context` while they run, so they lose it. The interpreted path of `make_ym_interval` and `make_dt_interval` loses it too: those classes carry the field, but their `nullSafeEval` still reads `origin.context`.

The same debugging run also showed:

- vanilla Spark loses the block the same way when whole-stage codegen is off (`ProjectExec` also builds its projection on the executor), so the defect is upstream;
- today's master already loses it for `SELECT ym / 2, ym / -1`, where `ym / 2` fuses and the declined `ym / -1` is evaluated by the merge projection.

So fusing `-1` now would not fix anything. It would move the solo `ym / -1` query from Spark's whole-stage code, whose error is right, to the fallback, whose error is not.

The fix is upstream: SPARK-61352, apache#60285 ("Keep an expression's own query context through serialization and rewrites", open). It makes the two divisions keep their context in a `SupportQueryContext` field, makes both divisions' interpreted and generated paths and the interpreted path of `make_ym_interval` and `make_dt_interval` read that stored context instead of `origin`, and makes `SupportQueryContext.copyTagsFrom` keep an expression's own valid context when a rule replaces a node with it. Once a sync brings it to this fork, the mixed query keeps its block, and `ym / -1` can fuse by rebuilding the arm, and `dt / -1` by its day-time counterpart, with nothing else to change.

The change is:

- `VarkaIntervalCompiler.divide`: still declines `-1`. The decline string and the method comment now give the reason: "interval divided by -1 raises at Int.MinValue, and a declined batch's fallback would raise it without its SQL context (VARKA-414)".
- `VarkaExpressionCompilerSuite`: checks the new string for a `-1` divisor of type `INT`, `SMALLINT` and `TINYINT`.
- `sql/varka/plans/m8/VARKA-414.md` section 9 records the run: both errors, the stack, the mechanism, the scored predictions and the arm's code. Section 10 records the owner's decision to fix it upstream and what SPARK-61352 changes.
- `sql/varka/plans/m8/PLAN.md`: row 414 stays Started, with one thing left, fusing `ym / -1` and `dt / -1` after the sync that brings SPARK-61352. The defect live on master is a new entry in the milestone's debt register, owned by SPARK-61352.
- `sql/varka/width_audit.json` changes only by the laptop's JDK update to 25.0.5, under which the `cast#N` and `opc=N` numbers in the audit's "not supported" lines move and the recorded JDK string changes. With those numbers set aside, no line changes. The change disappears once master's file is regenerated on that JDK.

### Why are the changes needed?

Varka promises that a query raises the same error Spark raises, the `== SQL ==` block that points at the failing expression included. The block went missing when `-1` was fused, and nobody knew why. The old decline reason pointed at the wrong place, and the run shows that the arm cannot fix the loss. The loss also reaches a query that master already serves, so the record has to say where the fix is and what is left once it arrives.

### Does this PR introduce _any_ user-facing change?

No. `ym / -1` stays unfused as before. Only the decline reason text changes, and it shows only in Varka's diagnostics.

### How was this patch tested?

Step 1 was a debugging run on a laptop. It added a temporary test to `VarkaYmDivideSuite`, which is not part of this PR, and ran it twice. The first run used the rebuilt arm and printed both engines' error fields and the stacks of the raises. The second run used the arm reverted, and covered the serialization round trip, Spark with `spark.sql.codegen.wholeStage=false`, and the mixed `ym / 2, ym / -1` query. `VARKA-414.md` section 9 quotes the results.

On the branch before the review round:

- `VarkaExpressionCompilerSuite`, `VarkaCoverageSuite`, `VarkaIrFuzzSuite` passed.
- `VarkaYmDivideSuite` and `VarkaCoverageDifferentialSuite` passed. The existing test there still checks that `ym / -1` stays unfused and that both engines raise the same error, compared in full: condition, state, parameters, the message with its context block, and the class.
- `dev/varka_matrix.sh --module sql --suites VarkaYmDivideSuite` passed under `checkIntOverflow=false`, `lanesOverride=4`, `lanesOverride=16` and `narrowLanes=false`, and `VarkaExpressionCompilerSuite` passed under `checkIntOverflow=false`. No `skips.tsv` line is needed, because nothing new fuses.

After the review round, `VarkaExpressionCompilerSuite` passes (174 tests), `dev/varka_plan_lint.py` finds nothing, and `dev/varka_push_check.py` passes.

No test is added for the mixed query. The PR changes no behaviour, and that query's cross-engine difference is the known defect in the debt register: a test for it would fail until the sync brings SPARK-61352, and is added with that sync.

Review: `/code-review high` found ten items on this PR, triaged in one round. Fixed:

- section 10's upstream option said that mixing in `SupportQueryContext` would be enough; it is not, since `make_ym_interval` has the field and its interpreted path still loses the context. Section 10 now records the decided fix, SPARK-61352, and what it changes;
- section 9 named only the two divisions as losing the context; it now names the interpreted path of `make_ym_interval` and `make_dt_interval` too;
- row 414's "left" named an open choice; it now names the one step left, fusing `-1` after the sync;
- the defect live on master was recorded only in the row's plan; it is now in the debt register, with what was run and what was inferred (`ym / 0`, a zero column divisor and the day-time division were not run);
- the decline test covered only an `INT` `-1`; it now covers `SMALLINT` and `TINYINT` too;
- the `VarkaColumnarToRowExec.scala` line citations pointed at the wrong lines, and one line of the plan ran past 100 columns;
- this description claimed an `emitted_bytes.json` change the net diff does not have, did not explain the `width_audit.json` change, and its title described the old reason.

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

Generated-by: Claude Code (Opus 5.5)
@MaxGekk

MaxGekk commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

@dongjoon-hyun @yaooqinn @peter-toth could you take a look? The interval division built its error context from origin.context when it was evaluated, so on executors, where the origin is lost when the expression is serialized, INTERVAL_DIVIDED_BY_ZERO and INTERVAL_ARITHMETIC_OVERFLOW arrived without the SQL fragment. IntervalDivide now keeps its context as SupportQueryContext, like the other arithmetic. SupportQueryContext.copyTagsFrom now copies the replaced node's context only when the expression has none of its own, since it used to overwrite it. That matters when a rule such as SimplifyCasts replaces a node with an existing expression.

@dongjoon-hyun

Copy link
Copy Markdown
Member

Sure, @MaxGekk .

@dongjoon-hyun dongjoon-hyun 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.

Thank you for the fix, @MaxGekk. I didn't find a correctness issue in the interval expressions themselves. Most of my comments are about the shared SupportQueryContext.copyTagsFrom change, because it applies to every SupportQueryContext expression, not only the interval ones.

  1. Performance: hasOwnQueryContext calls SQLQueryContext.isValid, which can scan the whole SQL text on every copyTagsFrom call, i.e. on the driver's tree-transform hot path.
  2. Behavior change: when a rule replaces a node with an existing child (e.g. SimplifyCasts), the error context now moves from the outer node to the inner expression. This affects SQL UDF bodies and ANSI expressions under a same-type cast, but it is not mentioned in the PR description and not covered by tests.
  3. Minor: the IntervalDivide doc wording, a duplicated validity filter, the sibling Multiply*Interval operators, and the test structure.

Please see the inline comments for details. These are based on reading the code; I haven't run the scenarios locally.

…s other review comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MaxGekk MaxGekk changed the title [SPARK-61352][SQL] Keep an expression's own query context through serialization and rewrites [SPARK-61352][SQL] Keep the query context of interval errors after serialization and rewrites Nov 11, 2026
@MaxGekk

MaxGekk commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Thank you for the review, @dongjoon-hyun. You're right that the shared rule moved contexts well beyond the interval expressions. In b43ba62 I narrowed it instead of documenting that: SupportQueryContext.copyTagsFrom now copies the replaced node's context unless it is None. That is all the interval division needs, since the non-ANSI Divide it replaces has none. A replaced node with a context still gives it to its replacement, as on master, so the ANSI expressions under a same-type cast, the DataFrame API and SQL function bodies keep their current contexts. The isValid scan and the duplicated filter are gone with it. The rest is addressed inline, and the PR description is updated.

@peter-toth peter-toth 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 for the PR, @MaxGekk!

IntervalDivide now keeps its query context in a SupportQueryContext field, and copyTagsFrom no longer overwrites a context with None. I ran the description's queries in ANSI and non-ANSI mode, with whole-stage codegen on and off. On the base, with codegen off, both divisions raise with an empty context. On this head every case reports its fragment, and the three new tests fail on the base.

Non-blocking

  • 1. One user-visible change is missing from the description: under ANSI, CAST(<division> AS INTERVAL YEAR TO MONTH) now reports the whole CAST(...) as its fragment. On the base it reported the division (with codegen on), since the division didn't take the cast's context. That matches ANSI Add under a same-type cast, so the behavior is fine. But the "as before" in the copyTagsFrom paragraph doesn't hold for the division, and the user-facing section should list it.

@github-actions github-actions Bot added the SQL label Nov 11, 2026
@MaxGekk

MaxGekk commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Thank you for the review and for running the queries, @peter-toth. Good catch on 1: the "as before" did not hold for the division. I updated the description: the copyTagsFrom paragraph now says that under ANSI the division takes the cast's context too, as ANSI Add does, and the user-facing section lists that the fragment of CAST(<division> AS INTERVAL YEAR TO MONTH) is now the whole CAST(...), where it was the division with whole-stage codegen.

@dongjoon-hyun dongjoon-hyun 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.

Thank you for addressing my comments, @MaxGekk. I reviewed the latest commit, b43ba62, and left 2 more inline comments, continuing the numbering of my first review. I left out the topics already discussed in the threads above and in @peter-toth's review.

  1. Shared expressions: IntervalDivide L744: the division now keeps its context in the mutable queryContext field, so copyTagsFrom can overwrite it in place on an instance shared with a temp view or a parent Dataset, and the error of one query then reports the CAST context of another. This predates the PR for ANSI Add and the other SupportQueryContext expressions, but the division was not affected before, so a follow-up JIRA may be enough.
  2. Tests: QueryExecutionAnsiErrorsSuite L119: the new tests check only SQL text contexts, not a DataFrameQueryContext from the Column API.

These are based on reading the code; I haven't run the scenarios locally.

MaxGekk and others added 2 commits November 11, 2026 20:18
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@spark-test spark-test left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review summary

This PR moves the interval divisions onto the serializable SupportQueryContext field and narrows SupportQueryContext.copyTagsFrom so that it copies only a defined context. Reading the current code, both evaluation paths of the divisions and the interpreted paths of make_ym_interval and make_dt_interval now take their context from that field. The earlier review threads are addressed in the code: the validity scan and the duplicated filter are gone, a replaced node that has a context still hands it on, and the tests build one instance per form, share their queries through a helper, and cover the Column API. The shared-instance overwrite and the sibling interval operators stay out of this PR, as its description says, tracked in SPARK-61467, SPARK-61439 and SPARK-61196.

The one finding is a test gap. The new unit test checks four of the six interpreted division branches, so a year-month interval divided by a decimal and a day-time interval divided by a float or double have no test that fails if their calls go back to origin.context. Two more cases in the existing list close it.

Findings

1 total: 0 P0, 0 P1, 0 P2, 1 P3.

Nit (P3)

  • Context test misses the year-month-by-decimal and day-time-by-fractional division branches — sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/IntervalExpressionsSuite.scala:549-555 — see inline.

PR description suggestions

  • The user-facing section describes the moved fragment only for a written CAST(...) under ANSI, but same-type casts that Spark adds itself also give an interval division their context once the optimizer removes them. Under ANSI, a SQL function's return-type cast makes a division body report the call site. Whatever the session's ANSI setting, the ANSI column cast of a persistent view created WITH SCHEMA COMPENSATION, the default mode, makes a division inside the view report the view reference in the outer query. In both cases whole-stage code used to report the division's own fragment in the function body or the view text. Consider listing these cases; the copyTagsFrom paragraph's statement that the body of a SQL function keeps its context as before does not hold when the body is an interval division.

Generated by Omnigent on Databricks

@dongjoon-hyun dongjoon-hyun 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.

Thank you for the updates, @MaxGekk. I reviewed the latest commit, 340982c, and left 3 more inline comments, continuing the numbering of my previous reviews. I left out the topics already discussed in the threads above and in the other reviews.

  1. try_cast: QueryExecutionAnsiErrorsSuite L125: a same-type try_cast also gives the interval division its context, whatever the session's ANSI setting, so the error points at the whole try_cast(...). The user-facing section does not list this case.
  2. Tests: IntervalExpressionsSuite L570: the test copies the same-type case of SimplifyCasts instead of running the rule.
  3. Minor: QueryExecutionAnsiErrorsSuite L125-144: the year-month and day-time checkError blocks could share one loop, as the new test in QueryExecutionErrorsSuite does.

These are based on reading the code; I haven't run the scenarios locally.

MaxGekk and others added 3 commits November 20, 2026 09:05
… itself, and share one loop

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MaxGekk

MaxGekk commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Thank you for the review, @dongjoon-hyun. Addressed in 0e77f68, with replies inline. While there I also tightened the rule in 8a895b3: copyTagsFrom now copies a replaced node's context only when it has an origin, that is a SQL text and a start index, the O(1) test you suggested earlier. So a same-type ANSI cast built outside an origin no longer replaces the division's context with an empty one. The PR description is updated.

@MaxGekk

MaxGekk commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

@dongjoon-hyun, when you have a moment, could you take another look? Your last round is addressed in 0e77f68 and 8a895b3, with replies inline, and I merged master in 2ade259. CI is green now.

@dongjoon-hyun dongjoon-hyun 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.

+1, LGTM. Thank you, @MaxGekk.

I checked the latest commit (2ade259) and found no correctness issue:

  • Executor path: rebuilding a deserialized node (e.g. BindReferences) copies the serialized context as is. hasOrigin passes for a DataFrameQueryContext and for a SQL context that the parser builds with its text and start index.
  • Analyzer path: both the fixed-point analyzer and the single-pass resolver build the division under the origin of the Divide, so a division that replaces a non-ANSI Divide (no context) keeps its own.
  • No null context: the queryContext of IntervalDivide, MakeYMInterval and MakeDTInterval can no longer be None, so getContextOrNull() does not return null for them.

I left three minor nits, none of them blocking:

  1. The SimplifyCasts forms of the new test do not check that the cast was removed.
  2. The hasOrigin scaladoc describes the cost of SQLQueryContext.isValid inaccurately.
  3. The copyTagsFrom comment says "raises in every mode", which only holds for the interval expressions.

{ val e = newExpr(); Cast(e, e.dataType, None, EvalMode.ANSI) } -> context
).map { case (cast, expected) =>
val plan = Project(Seq(Alias(cast, "c")()), OneRowRelation())
SimplifyCasts(plan).expressions.head.children.head -> expected

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.

nit: Nothing here checks that SimplifyCasts actually removed the cast. If it kept one, .children.head would be the Cast itself, and evaluating it would make the division raise with its own context. The LEGACY form and the ANSI form built outside withOrigin expect context, so they would still pass without testing the copyTagsFrom branches for a context that is missing or has no origin. Only the ANSI and TRY forms would fail. How about asserting that the result is not a Cast?

val replaced = SimplifyCasts(plan).expressions.head.children.head
assert(!replaced.isInstanceOf[Cast], s"SimplifyCasts kept $cast")
replaced -> expected

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in 0e163ca: the test now asserts that the result is not a Cast, so the LEGACY form and the ANSI form built outside withOrigin really reach copyTagsFrom.

Comment on lines +762 to +764
* Whether `context` comes from an origin. A SQL context built from an empty "Origin" has no
* text and no start index. This test is O(1), unlike `SQLQueryContext.isValid`, which counts
* the code points of a text with supplementary characters, so it can run on every transform.

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.

nit: SQLQueryContext.isValid calls hasSupplementary(text), i.e. text.codePointCount(0, text.length), every time, not only for a text with supplementary characters. That is O(1) only for a Latin-1 string. A text with any non-Latin-1 character, e.g. a CJK alias or comment, makes it O(L) even without supplementary characters. How about "unlike SQLQueryContext.isValid, which counts the code points of any non-Latin-1 text"?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in 0e163ca: it now says isValid counts the code points of any non-Latin-1 text.

Comment on lines +746 to +749
// It is copied only when the replaced node has one with an origin: a node without a
// context, such as a non-ANSI `Divide` that the analyzer turns into an interval
// division, or with one built from an empty "Origin", would otherwise leave the
// expression that replaces it, which raises in every mode, without a usable one.

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.

nit: This comment is on the trait, so it covers every SupportQueryContext (Cast, Sum, ElementAt, ANSI arithmetic, ...), but "which raises in every mode" only holds for the interval expressions. Most of the others raise only under ANSI. How about scoping it to the example, e.g. "would otherwise leave the expression that replaces it, such as an interval division, which raises in every mode, without a usable one"?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done in 0e163ca: "which raises in every mode" is now scoped to the interval division example.

…mments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MaxGekk

MaxGekk commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Thank you for the review and the approval, @dongjoon-hyun. All three nits are addressed in 0e163ca, with replies inline: the test now asserts that SimplifyCasts removed the cast, and the two comments are fixed. The change touches only the test and the comments.

dongjoon-hyun pushed a commit that referenced this pull request Nov 23, 2026
…rialization and rewrites

### What changes were proposed in this pull request?

`DivideYMInterval` and `DivideDTInterval` share the `IntervalDivide` trait. Both build the context for their errors (`INTERVAL_ARITHMETIC_OVERFLOW.WITH_SUGGESTION`, `INTERVAL_DIVIDED_BY_ZERO`) from `origin.context`, read at evaluation time in the interpreted path and at code-generation time in `doGenCode`. This PR makes the division keep its context the way the other arithmetic expressions do:

- `IntervalDivide` now mixes in `SupportQueryContext`, with `initQueryContext() = Some(origin.context)`. The division raises in every mode, so the context is set unconditionally rather than only under ANSI as in `Divide`.
- The interpreted `evalFunc` of both classes calls `getContextOrNull()`, and `doGenCode` calls `getContextOrNullCode(ctx)`, in place of `origin.context`.
- `SupportQueryContext.copyTagsFrom`, shared by every expression with a query context, now copies the context of the node it replaces only when that node has one that comes from an origin (`SupportQueryContext.hasOrigin`: a SQL context with a text and a start index, or any other context such as a `DataFrameQueryContext`). Until now it also copied `None`, and a context built from an empty `Origin`. `TreeNode.transformDown`/`transformUp` call `afterRule.copyTagsFrom(this)` whenever a rule replaces a node, and the replaced node can have no context: the non-ANSI `Divide` that the analyzer (`BinaryArithmeticWithDatetimeResolver`) turns into `DivideYMInterval` / `DivideDTInterval` has a `queryContext` of `None`, and so does a non-ANSI cast that `SimplifyCasts` replaces with `make_ym_interval(...)`. Copying it left the division or `make_*_interval`, which raise in every mode, with no context. Today the division still has one, because it reads `origin.context`; once it reads the field, copying `None` alone would make `select interval 2147483647 month / 0.5` in `nonansi/interval.sql` lose it.

  The copy still does what SPARK-39166 added it for. On an executor the deserialized expression has an empty `origin`, and a transform there (`BindReferences` while a projection is built) rebuilds the node, which then takes the serialized context. A replaced node with a context still gives it to its replacement, so the other ANSI expressions, the DataFrame API and the body of a SQL function keep their contexts as before. Under ANSI, `SimplifyCasts` dropping `CAST(<ym> / -1 AS INTERVAL YEAR TO MONTH)` now leaves the division with the cast's context too, as ANSI `Add` gets under a same-type cast. So does a same-type `try_cast` in every mode, since `Cast.ansiEnabled` holds for `EvalMode.TRY` unless it casts a string to a fractional or datetime type, so an interval-to-interval `try_cast` has a context even with `spark.sql.ansi.enabled=false`. Before, the division read `origin.context`, so with whole-stage codegen it reported its own fragment there.

  Effect on other expressions: only a `SupportQueryContext` expression with a context of its own that a rule returns in place of a node without one now keeps its context instead of losing it. Such a node is a non-ANSI or `try_*` form, or one built outside an origin, whose replacement has a context in that mode, such as the interval expressions here. Everything else behaves as before.
- Same pattern in two siblings: the interpreted paths of `MakeYMInterval` and `MakeDTInterval` passed `origin.context`, although both classes are already `SupportQueryContext` and their generated code already uses the field. Both now call `getContextOrNull()`.

Not fixed here: `copyTagsFrom` sets the context of the expression a rule returns in place, and that instance can be shared with a temp view or a parent Dataset, so a division shared that way can report the context of another query that removed a cast over it. This predates the PR for the other `SupportQueryContext` expressions, such as ANSI `Add`, and is tracked in SPARK-61467.

### Why are the changes needed?

`TreeNode` does not implement `java.io.Serializable`, so Java serialization skips its fields. When an expression is deserialized, `TreeNode`'s constructor runs again and sets `origin` from `CurrentOrigin.get`, which is empty on an executor. `SupportQueryContext` exists for this reason (SPARK-39166): its context is a field of the concrete, serializable expression, so it survives the trip to the executor.

The interval divisions never used it. Whole-stage codegen hides the problem, because it generates code on the driver and puts the context into the references array. Any projection built on the executor from the deserialized expression, though, raises the error with an empty context and no `== SQL ==` block. That includes `ProjectExec` and the other operators when `spark.sql.codegen.wholeStage=false`, and interpreted projections. For example:

```sql
SET spark.sql.ansi.enabled=true;
SET spark.sql.codegen.wholeStage=false;
SELECT CAST(CAST(id - 2147483648 AS INT) AS INTERVAL MONTH) / -1 FROM range(1);
```

raises `[INTERVAL_ARITHMETIC_OVERFLOW.WITH_SUGGESTION] ... SQLSTATE: 22015` with a query context whose fragment is empty and whose start and stop are -1. With whole-stage codegen on, the same query reports the fragment and the caret. `CAST(id + 1 AS INTERVAL DAY) / CAST(id AS INT)` gives `INTERVAL_DIVIDED_BY_ZERO` with the same gap. `make_ym_interval` / `make_dt_interval` overflows lose the context the same way, but only in interpreted evaluation, since their generated code already used the field. SPARK-60746 made both evaluation paths raise the same condition with a context. This PR closes the remaining gap, where that context is lost once the expression is serialized. The gap is older than SPARK-60746: released versions read `origin.context` in these classes too.

The gap was found while comparing errors from a columnar engine's fallback projections, which are built on the executor, against Spark's own whole-stage code.

A grep for `origin.context` across the non-test sources under `sql/` finds no other evaluation-time readers. The remaining hits are analysis-time error builders that run on the driver. SPARK-61196 (open) plans to pass a context to the overflow errors of interval add, subtract and negate. It should take it from a `SupportQueryContext` field as here, not from `origin.context`, or it will have the same gap.

### Does this PR introduce _any_ user-facing change?

Yes. Interval division by a number now reports its SQL query context (the `== SQL ==` block, and the fragment and position in the error's `queryContext`) when it overflows or divides by zero in a projection built on the executor, for example with `spark.sql.codegen.wholeStage=false`. Before, those errors had an empty context there. `make_ym_interval` and `make_dt_interval` already kept their context in generated code; they now keep it in interpreted evaluation too (the codegen fallback, or `spark.sql.codegen.factoryMode=NO_CODEGEN`). In non-ANSI mode, an interval division or `make_ym_interval` / `make_dt_interval` under a cast to its own type, which `SimplifyCasts` removes, keeps a context instead of losing it. Under ANSI, an interval division under such a cast now reports the whole `CAST(...)` as its fragment, as the other ANSI arithmetic does, where before, with whole-stage codegen, it reported the division. The same holds for a same-type `try_cast` in either mode: the query still fails, since `try_cast` does not catch an error of its child, and the fragment is the whole `try_cast(...)`. The error condition, SQLSTATE and message parameters do not change.

### How was this patch tested?

New tests:

- `IntervalExpressionsSuite`, "SPARK-61352: an interval error keeps its query context": builds each expression under `withOrigin` and evaluates it outside, so the serialization round trip in `ExpressionEvalHelper` cannot restore the origin from `CurrentOrigin`. It checks for the `== SQL (line 1, position 8) ==` block in the interpreted, mutable-projection and unsafe-projection modes. Cases: year-month `MinValue / -1` (integral, double and decimal), year-month `/ 0`, day-time `MinValue / -1` (long, decimal and double), day-time `/ 0`, so that each interpreted division branch is reached, `make_ym_interval(2147483647, 0)`, `make_dt_interval(2147483647)`. Each case is checked in three forms: as built; after `SimplifyCasts`, run on a one-column `Project`, removes a same-type `Cast` around it: with an ANSI or a TRY cast, whose context the expression takes, with a non-ANSI one, which has none, and with an ANSI cast built outside `withOrigin`, whose context has no origin, so the expression keeps its own in the last two; and after a `makeCopy` of a deserialized copy, which rebuilds the node with an empty `origin` as a transform on an executor does. Each form is built from a fresh instance, since `copyTagsFrom` changes the instance a rule returns.
- `QueryExecutionAnsiErrorsSuite`, "SPARK-61352: an interval division error keeps its query context": runs `CAST(CAST(id - 2147483648 AS INT) AS INTERVAL MONTH) / -1` and `CAST(id + 1 AS INTERVAL DAY) / CAST(id AS INT)` end to end, each bare and inside a `CAST` and a `try_cast` to its own type (`INTERVAL YEAR TO MONTH`, `INTERVAL DAY TO SECOND`), with whole-stage codegen on and off, from one case table, and checks the condition, parameters and the `ExpectedContext` fragment: the division, or the whole `CAST(...)` / `try_cast(...)`, whose context the division takes. It also runs `spark.range(1).select(expr("CAST(id + 1 AS INTERVAL DAY)") / $"id".cast("int"))` in both modes and checks the `DataFrameQueryContext`: fragment `div` and the call site. The operands read a column, so they are not constant-folded on the driver.
- `QueryExecutionErrorsSuite`, "SPARK-61352: an interval error keeps its query context in non-ANSI mode": the same two divisions plus `make_ym_interval(CAST(id AS INT) + 178956971, 0)` and `make_dt_interval(CAST(id AS INT) + 106751992)`, bare and inside a `CAST` to their own type, whose context they keep, and inside a `try_cast`, whose context they take, under `spark.sql.ansi.enabled=false`, with whole-stage codegen on and off.

With `copyTagsFrom` copying `None` again, the unit test fails on the non-ANSI cast form: the expression under the cast reports no context. Without the `hasOrigin` check, it fails on the ANSI cast built outside `withOrigin`. The two suites share the queries and the expected-context helper through `IntervalErrorContextTestUtils`.

Existing suites pass: `IntervalExpressionsSuite`, `ArithmeticExpressionSuite`, `DecimalExpressionSuite`, `SimplifyCastsSuite`, `CastWithAnsiOnSuite`, `CastWithAnsiOffSuite`, `TryCastSuite`, `QueryExecutionErrorsSuite`, `QueryExecutionAnsiErrorsSuite`, the "Query context" tests of `SQLQuerySuite` (SPARK-39166 and its follow-ups, which raise from a projection built on the executor), and the whole `SQLQueryTestSuite` with no golden file changes. Its one failure locally, `udtf/udtf.sql - Python UDTFs` query #29, is the local Python's `ValueError` wording for `list.index` (`list.index(x): x not in list` against the expected `'input' is not in list`), unrelated to this change. `catalyst/scalastyle`, `catalyst/Test/scalastyle` and `sql/Test/scalastyle` pass.

```
build/sbt 'catalyst/testOnly *IntervalExpressionsSuite *ArithmeticExpressionSuite *DecimalExpressionSuite *SimplifyCastsSuite *CastWithAnsiOnSuite *CastWithAnsiOffSuite *TryCastSuite' \
  'sql/testOnly *QueryExecutionErrorsSuite *QueryExecutionAnsiErrorsSuite' \
  'sql/testOnly org.apache.spark.sql.SQLQuerySuite -- -z "Query context"' \
  'sql/testOnly org.apache.spark.sql.SQLQueryTestSuite'
```

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

Generated-by: Claude Code (Opus 5.5)

Closes #60285 from MaxGekk/SPARK-61352-interval-divide-context.

Lead-authored-by: Maxim Gekk <max.gekk@gmail.com>
Co-authored-by: t <t@example.com>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>

(cherry picked from commit 8621489)
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>


skip-checks: true
dongjoon-hyun pushed a commit that referenced this pull request Nov 23, 2026
…rialization and rewrites

### What changes were proposed in this pull request?

`DivideYMInterval` and `DivideDTInterval` share the `IntervalDivide` trait. Both build the context for their errors (`INTERVAL_ARITHMETIC_OVERFLOW.WITH_SUGGESTION`, `INTERVAL_DIVIDED_BY_ZERO`) from `origin.context`, read at evaluation time in the interpreted path and at code-generation time in `doGenCode`. This PR makes the division keep its context the way the other arithmetic expressions do:

- `IntervalDivide` now mixes in `SupportQueryContext`, with `initQueryContext() = Some(origin.context)`. The division raises in every mode, so the context is set unconditionally rather than only under ANSI as in `Divide`.
- The interpreted `evalFunc` of both classes calls `getContextOrNull()`, and `doGenCode` calls `getContextOrNullCode(ctx)`, in place of `origin.context`.
- `SupportQueryContext.copyTagsFrom`, shared by every expression with a query context, now copies the context of the node it replaces only when that node has one that comes from an origin (`SupportQueryContext.hasOrigin`: a SQL context with a text and a start index, or any other context such as a `DataFrameQueryContext`). Until now it also copied `None`, and a context built from an empty `Origin`. `TreeNode.transformDown`/`transformUp` call `afterRule.copyTagsFrom(this)` whenever a rule replaces a node, and the replaced node can have no context: the non-ANSI `Divide` that the analyzer (`BinaryArithmeticWithDatetimeResolver`) turns into `DivideYMInterval` / `DivideDTInterval` has a `queryContext` of `None`, and so does a non-ANSI cast that `SimplifyCasts` replaces with `make_ym_interval(...)`. Copying it left the division or `make_*_interval`, which raise in every mode, with no context. Today the division still has one, because it reads `origin.context`; once it reads the field, copying `None` alone would make `select interval 2147483647 month / 0.5` in `nonansi/interval.sql` lose it.

  The copy still does what SPARK-39166 added it for. On an executor the deserialized expression has an empty `origin`, and a transform there (`BindReferences` while a projection is built) rebuilds the node, which then takes the serialized context. A replaced node with a context still gives it to its replacement, so the other ANSI expressions, the DataFrame API and the body of a SQL function keep their contexts as before. Under ANSI, `SimplifyCasts` dropping `CAST(<ym> / -1 AS INTERVAL YEAR TO MONTH)` now leaves the division with the cast's context too, as ANSI `Add` gets under a same-type cast. So does a same-type `try_cast` in every mode, since `Cast.ansiEnabled` holds for `EvalMode.TRY` unless it casts a string to a fractional or datetime type, so an interval-to-interval `try_cast` has a context even with `spark.sql.ansi.enabled=false`. Before, the division read `origin.context`, so with whole-stage codegen it reported its own fragment there.

  Effect on other expressions: only a `SupportQueryContext` expression with a context of its own that a rule returns in place of a node without one now keeps its context instead of losing it. Such a node is a non-ANSI or `try_*` form, or one built outside an origin, whose replacement has a context in that mode, such as the interval expressions here. Everything else behaves as before.
- Same pattern in two siblings: the interpreted paths of `MakeYMInterval` and `MakeDTInterval` passed `origin.context`, although both classes are already `SupportQueryContext` and their generated code already uses the field. Both now call `getContextOrNull()`.

Not fixed here: `copyTagsFrom` sets the context of the expression a rule returns in place, and that instance can be shared with a temp view or a parent Dataset, so a division shared that way can report the context of another query that removed a cast over it. This predates the PR for the other `SupportQueryContext` expressions, such as ANSI `Add`, and is tracked in SPARK-61467.

### Why are the changes needed?

`TreeNode` does not implement `java.io.Serializable`, so Java serialization skips its fields. When an expression is deserialized, `TreeNode`'s constructor runs again and sets `origin` from `CurrentOrigin.get`, which is empty on an executor. `SupportQueryContext` exists for this reason (SPARK-39166): its context is a field of the concrete, serializable expression, so it survives the trip to the executor.

The interval divisions never used it. Whole-stage codegen hides the problem, because it generates code on the driver and puts the context into the references array. Any projection built on the executor from the deserialized expression, though, raises the error with an empty context and no `== SQL ==` block. That includes `ProjectExec` and the other operators when `spark.sql.codegen.wholeStage=false`, and interpreted projections. For example:

```sql
SET spark.sql.ansi.enabled=true;
SET spark.sql.codegen.wholeStage=false;
SELECT CAST(CAST(id - 2147483648 AS INT) AS INTERVAL MONTH) / -1 FROM range(1);
```

raises `[INTERVAL_ARITHMETIC_OVERFLOW.WITH_SUGGESTION] ... SQLSTATE: 22015` with a query context whose fragment is empty and whose start and stop are -1. With whole-stage codegen on, the same query reports the fragment and the caret. `CAST(id + 1 AS INTERVAL DAY) / CAST(id AS INT)` gives `INTERVAL_DIVIDED_BY_ZERO` with the same gap. `make_ym_interval` / `make_dt_interval` overflows lose the context the same way, but only in interpreted evaluation, since their generated code already used the field. SPARK-60746 made both evaluation paths raise the same condition with a context. This PR closes the remaining gap, where that context is lost once the expression is serialized. The gap is older than SPARK-60746: released versions read `origin.context` in these classes too.

The gap was found while comparing errors from a columnar engine's fallback projections, which are built on the executor, against Spark's own whole-stage code.

A grep for `origin.context` across the non-test sources under `sql/` finds no other evaluation-time readers. The remaining hits are analysis-time error builders that run on the driver. SPARK-61196 (open) plans to pass a context to the overflow errors of interval add, subtract and negate. It should take it from a `SupportQueryContext` field as here, not from `origin.context`, or it will have the same gap.

### Does this PR introduce _any_ user-facing change?

Yes. Interval division by a number now reports its SQL query context (the `== SQL ==` block, and the fragment and position in the error's `queryContext`) when it overflows or divides by zero in a projection built on the executor, for example with `spark.sql.codegen.wholeStage=false`. Before, those errors had an empty context there. `make_ym_interval` and `make_dt_interval` already kept their context in generated code; they now keep it in interpreted evaluation too (the codegen fallback, or `spark.sql.codegen.factoryMode=NO_CODEGEN`). In non-ANSI mode, an interval division or `make_ym_interval` / `make_dt_interval` under a cast to its own type, which `SimplifyCasts` removes, keeps a context instead of losing it. Under ANSI, an interval division under such a cast now reports the whole `CAST(...)` as its fragment, as the other ANSI arithmetic does, where before, with whole-stage codegen, it reported the division. The same holds for a same-type `try_cast` in either mode: the query still fails, since `try_cast` does not catch an error of its child, and the fragment is the whole `try_cast(...)`. The error condition, SQLSTATE and message parameters do not change.

### How was this patch tested?

New tests:

- `IntervalExpressionsSuite`, "SPARK-61352: an interval error keeps its query context": builds each expression under `withOrigin` and evaluates it outside, so the serialization round trip in `ExpressionEvalHelper` cannot restore the origin from `CurrentOrigin`. It checks for the `== SQL (line 1, position 8) ==` block in the interpreted, mutable-projection and unsafe-projection modes. Cases: year-month `MinValue / -1` (integral, double and decimal), year-month `/ 0`, day-time `MinValue / -1` (long, decimal and double), day-time `/ 0`, so that each interpreted division branch is reached, `make_ym_interval(2147483647, 0)`, `make_dt_interval(2147483647)`. Each case is checked in three forms: as built; after `SimplifyCasts`, run on a one-column `Project`, removes a same-type `Cast` around it: with an ANSI or a TRY cast, whose context the expression takes, with a non-ANSI one, which has none, and with an ANSI cast built outside `withOrigin`, whose context has no origin, so the expression keeps its own in the last two; and after a `makeCopy` of a deserialized copy, which rebuilds the node with an empty `origin` as a transform on an executor does. Each form is built from a fresh instance, since `copyTagsFrom` changes the instance a rule returns.
- `QueryExecutionAnsiErrorsSuite`, "SPARK-61352: an interval division error keeps its query context": runs `CAST(CAST(id - 2147483648 AS INT) AS INTERVAL MONTH) / -1` and `CAST(id + 1 AS INTERVAL DAY) / CAST(id AS INT)` end to end, each bare and inside a `CAST` and a `try_cast` to its own type (`INTERVAL YEAR TO MONTH`, `INTERVAL DAY TO SECOND`), with whole-stage codegen on and off, from one case table, and checks the condition, parameters and the `ExpectedContext` fragment: the division, or the whole `CAST(...)` / `try_cast(...)`, whose context the division takes. It also runs `spark.range(1).select(expr("CAST(id + 1 AS INTERVAL DAY)") / $"id".cast("int"))` in both modes and checks the `DataFrameQueryContext`: fragment `div` and the call site. The operands read a column, so they are not constant-folded on the driver.
- `QueryExecutionErrorsSuite`, "SPARK-61352: an interval error keeps its query context in non-ANSI mode": the same two divisions plus `make_ym_interval(CAST(id AS INT) + 178956971, 0)` and `make_dt_interval(CAST(id AS INT) + 106751992)`, bare and inside a `CAST` to their own type, whose context they keep, and inside a `try_cast`, whose context they take, under `spark.sql.ansi.enabled=false`, with whole-stage codegen on and off.

With `copyTagsFrom` copying `None` again, the unit test fails on the non-ANSI cast form: the expression under the cast reports no context. Without the `hasOrigin` check, it fails on the ANSI cast built outside `withOrigin`. The two suites share the queries and the expected-context helper through `IntervalErrorContextTestUtils`.

Existing suites pass: `IntervalExpressionsSuite`, `ArithmeticExpressionSuite`, `DecimalExpressionSuite`, `SimplifyCastsSuite`, `CastWithAnsiOnSuite`, `CastWithAnsiOffSuite`, `TryCastSuite`, `QueryExecutionErrorsSuite`, `QueryExecutionAnsiErrorsSuite`, the "Query context" tests of `SQLQuerySuite` (SPARK-39166 and its follow-ups, which raise from a projection built on the executor), and the whole `SQLQueryTestSuite` with no golden file changes. Its one failure locally, `udtf/udtf.sql - Python UDTFs` query #29, is the local Python's `ValueError` wording for `list.index` (`list.index(x): x not in list` against the expected `'input' is not in list`), unrelated to this change. `catalyst/scalastyle`, `catalyst/Test/scalastyle` and `sql/Test/scalastyle` pass.

```
build/sbt 'catalyst/testOnly *IntervalExpressionsSuite *ArithmeticExpressionSuite *DecimalExpressionSuite *SimplifyCastsSuite *CastWithAnsiOnSuite *CastWithAnsiOffSuite *TryCastSuite' \
  'sql/testOnly *QueryExecutionErrorsSuite *QueryExecutionAnsiErrorsSuite' \
  'sql/testOnly org.apache.spark.sql.SQLQuerySuite -- -z "Query context"' \
  'sql/testOnly org.apache.spark.sql.SQLQueryTestSuite'
```

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

Generated-by: Claude Code (Opus 5.5)

Closes #60285 from MaxGekk/SPARK-61352-interval-divide-context.

Lead-authored-by: Maxim Gekk <max.gekk@gmail.com>
Co-authored-by: t <t@example.com>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>

(cherry picked from commit 8621489)
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>
@dongjoon-hyun

Copy link
Copy Markdown
Member

Merge Summary:

Posted by merge_spark_pr.py

@dongjoon-hyun

Copy link
Copy Markdown
Member

Thank you, @MaxGekk . I merged to master/4.x/4.4. For the older release branches, we had better run the CIs.
Could you make backporting PRs for the Affected Versions you reported in the JIRA, please?

@MaxGekk

MaxGekk commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Thank you, @dongjoon-hyun. The commit doesn't cherry-pick to the older branches as is, since it builds on SPARK-60746 (#59956), which is in master, branch-4.x and branch-4.4 only and is a behavior change, so I'm porting the fix to their interval code instead:

branch-4.1, branch-4.0 and branch-3.5 lack more of the interval changes, so each would be a larger adaptation. Shall I do them too, or stop at 4.2?

@MaxGekk

MaxGekk commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

The branch-4.2 backport is #60848, ported the same way as #60847 for branch-4.3.

MaxGekk added a commit that referenced this pull request Nov 24, 2026
…er serialization and rewrites

### What changes were proposed in this pull request?

This is a backport of #60285 (SPARK-61352) to `branch-4.3`, adapted because `branch-4.3` doesn't have SPARK-60746 (#59956), on which the change on master builds. The interval divisions there still have their own checks instead of the `IntervalMathUtils.divide` overloads, so only the part of the fix that applies to that code is ported:

- `IntervalDivide` (`DivideYMInterval`, `DivideDTInterval`) now mixes in `SupportQueryContext`, with `initQueryContext() = Some(origin.context)`, set in every mode since the division raises in every mode.
- The interpreted `nullSafeEval` of both divisions calls `getContextOrNull()`, and their `doGenCode` calls `getContextOrNullCode(ctx)`, in place of `origin.context`. The same for the interpreted paths of `MakeYMInterval` and `MakeDTInterval`, which were already `SupportQueryContext`.
- `SupportQueryContext.copyTagsFrom` copies the context of the node it replaces only when that node has one with an origin (`SupportQueryContext.hasOrigin`), as on master, so that a replaced non-ANSI `Divide` or cast, which has none, no longer leaves the division without a context.

What differs from master: on this branch, an interval at its minimum divided by an integral `-1` raises `ARITHMETIC_OVERFLOW` in generated code and `INTERVAL_ARITHMETIC_OVERFLOW` in the interpreted path, and an overflow with a decimal or double divisor raises a plain `ArithmeticException` without a context. Both are unchanged here: unifying them is SPARK-60746, a behavior change that is not backported. The tests expect the errors of this branch.

Not fixed here, as on master: `copyTagsFrom` sets the context of the instance a rule returns in place, and that instance can be shared with another Dataset or a temp view, so a division shared that way can report the context of another query that removed a cast over it. This affects the other `SupportQueryContext` expressions too, and is tracked in SPARK-61467.

### Why are the changes needed?

`TreeNode` does not serialize `origin`, so a deserialized interval division on an executor has an empty one. Any projection built there, e.g. with `spark.sql.codegen.wholeStage=false`, raises `INTERVAL_DIVIDED_BY_ZERO` or the overflow error with an empty query context, without the `== SQL ==` block. For example, with ANSI on:

```sql
SET spark.sql.codegen.wholeStage=false;
SELECT CAST(id + 1 AS INTERVAL DAY) / CAST(id AS INT) FROM range(1);
```

### Does this PR introduce _any_ user-facing change?

Yes. Interval division keeps its SQL query context when it divides by zero, or overflows with an integral divisor, in a projection built on the executor; before, those errors had an empty context there. `make_ym_interval` and `make_dt_interval` keep their context in interpreted evaluation too. In non-ANSI mode, these expressions under a cast to their own type, which `SimplifyCasts` removes, keep a context instead of losing it. Under ANSI, an interval division under such a `CAST` now reports the whole `CAST(...)` as its fragment, as the other ANSI arithmetic does, where with whole-stage codegen it reported the division; a same-type `try_cast` does the same in both modes, although it does not suppress the error.

### How was this patch tested?

The tests of #60285, adapted to this branch:

- `IntervalExpressionsSuite`, "SPARK-61352: an interval error keeps its query context": year-month `MinValue / -1` and day-time `MinValue / -1L`, divisions by an integral, a decimal and a double zero, `make_ym_interval(2147483647, 0)` and `make_dt_interval(2147483647)`, each as built, under an ANSI, a TRY and a LEGACY same-type cast removed by `SimplifyCasts`, under an ANSI cast built without an origin, and after a `makeCopy` of a deserialized copy. The decimal and double `MinValue / -1` cases of master are left out, since they raise without a context on this branch. The test fails without the change.
- `QueryExecutionAnsiErrorsSuite` and `QueryExecutionErrorsSuite`, "SPARK-61352: ...": the divisions and `make_*_interval` end to end, bare and under a `CAST` and a `try_cast` to their own type, with whole-stage codegen on and off, and the Column API division with a `DataFrameQueryContext`. The year-month division expects `ARITHMETIC_OVERFLOW`, which generated code raises on this branch.

```
build/sbt 'catalyst/testOnly *IntervalExpressionsSuite *ArithmeticExpressionSuite *SimplifyCastsSuite *CastWithAnsiOnSuite *CastWithAnsiOffSuite *TryCastSuite' \
  'sql/testOnly *QueryExecutionErrorsSuite *QueryExecutionAnsiErrorsSuite' \
  'sql/testOnly org.apache.spark.sql.SQLQuerySuite -- -z "Query context"' \
  'sql/testOnly org.apache.spark.sql.SQLQueryTestSuite -- -z interval'
```

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

Generated-by: Claude Code (Claude Opus 5.5)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Closes #60847 from MaxGekk/SPARK-61352-4.3.

Authored-by: Max Gekk <max.gekk@gmail.com>
Signed-off-by: Max Gekk <max.gekk@gmail.com>
MaxGekk added a commit that referenced this pull request Nov 24, 2026
…er serialization and rewrites

### What changes were proposed in this pull request?

This is a backport of #60285 (SPARK-61352) to `branch-4.2`, the same as #60847 for `branch-4.3`, adapted because `branch-4.2` doesn't have SPARK-60746 (#59956), on which the change on master builds. The interval divisions there still have their own checks instead of the `IntervalMathUtils.divide` overloads, so only the part of the fix that applies to that code is ported:

- `IntervalDivide` (`DivideYMInterval`, `DivideDTInterval`) now mixes in `SupportQueryContext`, with `initQueryContext() = Some(origin.context)`, set in every mode since the division raises in every mode.
- The interpreted `nullSafeEval` of both divisions calls `getContextOrNull()`, and their `doGenCode` calls `getContextOrNullCode(ctx)`, in place of `origin.context`. The same for the interpreted paths of `MakeYMInterval` and `MakeDTInterval`, which were already `SupportQueryContext`.
- `SupportQueryContext.copyTagsFrom` copies the context of the node it replaces only when that node has one with an origin (`SupportQueryContext.hasOrigin`), as on master, so that a replaced non-ANSI `Divide` or cast, which has none, no longer leaves the division without a context.

What differs from master: on this branch, an interval at its minimum divided by an integral `-1` raises `ARITHMETIC_OVERFLOW` in generated code and `INTERVAL_ARITHMETIC_OVERFLOW` in the interpreted path, and an overflow with a decimal or double divisor raises a plain `ArithmeticException` without a context. Both are unchanged here: unifying them is SPARK-60746, a behavior change that is not backported. The tests expect the errors of this branch.

Not fixed here, as on master: `copyTagsFrom` sets the context of the instance a rule returns in place, and that instance can be shared with another Dataset or a temp view, so a division shared that way can report the context of another query that removed a cast over it. This affects the other `SupportQueryContext` expressions too, and is tracked in SPARK-61467.

### Why are the changes needed?

`TreeNode` does not serialize `origin`, so a deserialized interval division on an executor has an empty one. Any projection built there, e.g. with `spark.sql.codegen.wholeStage=false`, raises `INTERVAL_DIVIDED_BY_ZERO` or the overflow error with an empty query context, without the `== SQL ==` block. For example, with ANSI on:

```sql
SET spark.sql.codegen.wholeStage=false;
SELECT CAST(id + 1 AS INTERVAL DAY) / CAST(id AS INT) FROM range(1);
```

### Does this PR introduce _any_ user-facing change?

Yes. Interval division keeps its SQL query context when it divides by zero, or overflows with an integral divisor, in a projection built on the executor; before, those errors had an empty context there. `make_ym_interval` and `make_dt_interval` keep their context in interpreted evaluation too. In non-ANSI mode, these expressions under a cast to their own type, which `SimplifyCasts` removes, keep a context instead of losing it. Under ANSI, an interval division under such a `CAST` now reports the whole `CAST(...)` as its fragment, as the other ANSI arithmetic does, where with whole-stage codegen it reported the division; a same-type `try_cast` does the same in both modes, although it does not suppress the error.

### How was this patch tested?

The tests of #60285, adapted to this branch:

- `IntervalExpressionsSuite`, "SPARK-61352: an interval error keeps its query context": year-month `MinValue / -1` and day-time `MinValue / -1L`, divisions by an integral, a decimal and a double zero, `make_ym_interval(2147483647, 0)` and `make_dt_interval(2147483647)`, each as built, under an ANSI, a TRY and a LEGACY same-type cast removed by `SimplifyCasts`, under an ANSI cast built without an origin, and after a `makeCopy` of a deserialized copy. The decimal and double `MinValue / -1` cases of master are left out, since they raise without a context on this branch. The test fails without the change.
- `QueryExecutionAnsiErrorsSuite` and `QueryExecutionErrorsSuite`, "SPARK-61352: ...": the divisions and `make_*_interval` end to end, bare and under a `CAST` and a `try_cast` to their own type, with whole-stage codegen on and off, and the Column API division with a `DataFrameQueryContext`. The year-month division expects `ARITHMETIC_OVERFLOW`, which generated code raises on this branch.

```
build/sbt 'catalyst/testOnly *IntervalExpressionsSuite *ArithmeticExpressionSuite *SimplifyCastsSuite *CastWithAnsiOnSuite *CastWithAnsiOffSuite *TryCastSuite' \
  'sql/testOnly *QueryExecutionErrorsSuite *QueryExecutionAnsiErrorsSuite' \
  'sql/testOnly org.apache.spark.sql.SQLQuerySuite -- -z "Query context"' \
  'sql/testOnly org.apache.spark.sql.SQLQueryTestSuite -- -z interval'
```

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

Generated-by: Claude Code (Claude Opus 5.5)


Closes #60848 from MaxGekk/SPARK-61352-4.2.

Authored-by: Max Gekk <max.gekk@gmail.com>
Signed-off-by: Max Gekk <max.gekk@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants