Skip to content

[SPARK-60315][SQL] Fix inconsistent filter behavior with whole-stage codegen on and off when a conjunct is NULL - #59573

Closed
MaxGekk wants to merge 5 commits into
apache:masterfrom
MaxGekk:SPARK-60315-filter-null-conjunct
Closed

MaxGekk wants to merge 5 commits into
apache:masterfrom
MaxGekk:SPARK-60315-filter-null-conjunct

Conversation

@MaxGekk

@MaxGekk MaxGekk commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

What changes were proposed in this pull request?

This PR fixes inconsistent behavior of a filter between whole-stage codegen on and off: when an earlier conjunct of the condition is NULL on a row and a later one raises an error on that row, the query failed with codegen off but returned rows with codegen on. After this PR, codegen keeps evaluating the conjuncts after a NULL one, so it raises the error in that case too. An IS NOT NULL check that precedes the raising conjunct in the condition still drops the row first in both modes.

Whole-stage codegen of a filter condition (FilterExec) and of the FILTER clause of an aggregate function (AggregateCodegenSupport) generates each top-level conjunct separately and drops the row as soon as one of them is FALSE or NULL (if (isNull || !value) continue;). The interpreted path evaluates the whole condition with And.eval, which stops only at FALSE. So when an earlier conjunct is NULL and a later one raises on that row, the query fails with codegen off and returns rows with it on.

This PR changes the generated code so that only a FALSE conjunct stops the evaluation:

  • GeneratePredicateHelper gets six helpers: splitNotNullPreds (splits the condition into the IsNotNull checks and the other conjuncts, keeping the number of checks that precede each conjunct), mayRaise (whether an expression can raise an error, is nondeterministic or may have side effects, via ExprUtils.canEvaluateUnconditionally), nullConjunctFlag (a fresh flag name, or None), conjunctCheck (the per-conjunct check), withNullConjunctFlag (declares the flag before the checks and drops the row after them if it is set) and precedingNotNullChecks (the pending checks to generate before a conjunct).
  • A NULL conjunct sets the flag, and the remaining conjuncts are still evaluated: if (isNull) { flag = true; } else if (!value) continue;. The row is dropped after all of them: if (flag) continue;.
  • The flag is generated only when some conjunct can be NULL after binding, and a conjunct after the first such one, or one of the IsNotNull checks, can raise an error, is nondeterministic or may have side effects (ExprUtils.canEvaluateUnconditionally). Otherwise the evaluation after a NULL conjunct is not observable and the generated code is unchanged, e.g. for WHERE (a > 5 OR b > 5) AND c = 1 AND d = 2. The IsNotNull checks are never NULL and keep their early continue, so the tightened-nullability binding of the later conjuncts, and of the CSE precomputes, stays safe.
  • With the flag, once a conjunct that can be NULL has been generated, the IsNotNull checks that precede a later conjunct in the condition are generated before it when the conjunct or one of the checks can raise, as And.eval evaluates them, instead of lazily before the first conjunct that references their column. So a FALSE check drops the row before an error the later conjunct raises on it, as with codegen off (splitNotNullPreds keeps the number of checks that precede each conjunct, precedingNotNullChecks returns the pending ones). The conjuncts before the first one that can be NULL are never reached after a NULL conjunct, so the checks before them keep the lazy placement, and without the flag the generated code is unchanged. The placement is decided at code generation, so once a condition has a conjunct that can be NULL, the checks after it are evaluated in the order of the condition on every row, not only on rows where a conjunct is NULL; a row with no NULL conjunct can then change too, in both directions, always toward the codegen-off result.
  • With the flag, after a conjunct that can be NULL, an IS NOT NULL check on an expression (SPARK-51356) that is written after the conjunct containing the expression is no longer generated before that conjunct. It stays at its position, as And.eval evaluates it, so it does not raise an error on a row that the conjunct drops as FALSE.
  • Both code paths are changed: generatePredicateCode, which the aggregate FILTER clause also uses, and the CSE branch of FilterExec.doConsume, which the code comments require to stay in step with it.
  • New legacy config spark.sql.legacy.filterShortCircuitOnNullConjunct (internal, default false, version 4.4.0). Set to true, it restores the previous codegen behavior. The interpreted path is unchanged in both modes.

Join conditions and MergeRowsExec generate the whole condition through And.doGenCode, which already evaluates the right side after a NULL left side, so they are not changed.

Not fixed here, on master as well as after this PR:

  • With whole-stage codegen on, an IS NOT NULL check on a column is generated just before the first conjunct that references the column, so WHERE x IS NOT NULL AND y + 1 > 0 AND x > 0 raises ARITHMETIC_OVERFLOW with codegen on and drops the row with codegen off. That is tracked in SPARK-60329. The check is also generated before that conjunct when it is written after it, and so before the conjuncts between that one and its own position, and a check on an expression over the column does the same through a synthetic check on the column. So after a NULL conjunct the evaluation can still drop the row where codegen off raises; the migration guide entry lists this as the exception to the order of the condition.
  • Before the first conjunct that can be NULL, including that conjunct itself, or with the legacy config, an IS NOT NULL check on an expression is still generated before the first conjunct that contains the expression, even when it is written after it, so WHERE coalesce(b, cast(s AS INT)) < 0 AND cast(s AS INT) IS NOT NULL raises CAST_INVALID_INPUT with codegen on and drops the row with codegen off on (b, s) = (1, 'x'). That is tracked in SPARK-60377.
  • With whole-stage codegen off, GeneratePredicate evaluates a subexpression shared by several conjuncts before the condition, so WHERE NOT (a > 0 AND b > 0) AND b < 0 AND y + 1 > 0 AND y + 1 > -1 raises ARITHMETIC_OVERFLOW with codegen off and returns no rows with codegen on, where the FALSE b < 0 stops the evaluation. That is tracked in SPARK-60392.
  • Whole-stage codegen evaluates the common subexpressions of the update expressions of an aggregate function before its FILTER clause, so SELECT avg(y + 1) FILTER (WHERE b < 0) FROM t raises ARITHMETIC_OVERFLOW with codegen on and returns NULL with codegen off. That is tracked in SPARK-60393.
  • The interleaving of the checks and the conjuncts is mirrored by hand in generatePredicateCode and in the CSE branch of FilterExec.doConsume. SPARK-60394 is to compute it once for both.

SQL standard

  • 7.11 <where clause>, GR 2 (and 10.9 <aggregate function>, GR 4a, for <filter clause>): the search condition is effectively evaluated for each row, and the result keeps the rows for which it is True.
  • 6.35 <boolean value expression>, Table 11: Unknown AND True is Unknown, Unknown AND False is False. After an Unknown conjunct the result of the search condition still depends on the remaining ones.
  • 9075-1 "Rule evaluation order" (SQL-92 3.3.4.4): only the inessential parts, those not needed to determine the result of the expression or search condition, may be skipped, and whether their exceptions are raised is implementation-dependent. After a NULL conjunct the rest is essential. The order of evaluation is implementation-dependent too, but in every order the raising conjunct is either evaluated first or is still essential, so the exception is raised. Only a FALSE conjunct makes the rest inessential.

Other DBMSes

Table t(a INT, b INT, y) with rows (NULL, 1, <raises>) and (0, 1, <ok>). <E> raises on the first row:

  • y + 1 > 0 with y at the maximum of its type: INT, or BIGINT on MySQL and MariaDB, which widen INT + INT;
  • 10 / y > 0 with y = 0 on Oracle, whose NUMBER does not overflow at 32 bits;
  • abs(y) > 0 with y at the minimum BIGINT on SQLite, where + switches to floating point.

The images and credentials are those of connector/docker-integration-tests.

Query PostgreSQL 18.2 MySQL 9.6.0 MariaDB 12.2.2 SQL Server 2022 Oracle Free 23.26 DB2 11.5.9 H2 2.3.232 Derby 10.16 SQLite 3.46
WHERE NOT (a > 0 AND b > 0) AND <E> skip skip skip raise skip raise raise skip skip
WHERE <E> AND NOT (a > 0 AND b > 0) raise raise raise raise skip raise raise skip raise
WHERE a > 0 AND <E> skip skip skip skip skip raise raise skip skip
WHERE b < 0 AND <E> (FALSE first) - - - - - raise - - -
count(a) FILTER (WHERE NOT (a > 0 AND b > 0) AND <E>) raise n/a n/a n/a raise n/a raise n/a skip

"-" means no error and an empty result; "n/a" means the FILTER clause is not supported.

  • In WHERE, most engines drop the row at the NULL conjunct. Oracle and Derby do it even when the raising conjunct is written first, so they reorder.
  • DB2 and H2 raise. SQL Server raises for the JIRA's shape but not for a plain a > 0 first.
  • For the aggregate FILTER clause, PostgreSQL, Oracle and H2 evaluate the whole AND and raise, as this PR does.

We considered the opposite fix: make the interpreted path stop at the first NULL conjunct too. It matches most engines' WHERE behavior, but it departs from the standard's text and from what Spark already does with codegen off. Setting spark.sql.legacy.filterShortCircuitOnNullConjunct to true only restores the previous whole-stage codegen behavior; with whole-stage codegen off, the query still raises.

Why are the changes needed?

The same query must not raise with whole-stage codegen off and return rows with it on (SPARK-60315). Reproducer (ANSI mode):

CREATE TABLE t USING parquet AS
  SELECT * FROM VALUES (NULL, 1, 2147483647), (0, 1, 0) AS v(a, b, y);
-- The rows can be written to different files, and `NOT (a > 0 AND b > 0)` is pushed down as
-- `a <= 0 OR b <= 0`, which skips the first row's file by its statistics.
SET spark.sql.parquet.filterPushdown=false;

SET spark.sql.codegen.wholeStage=true;
SELECT a FROM t WHERE NOT (a > 0 AND b > 0) AND y + 1 > 0;
-- before: 0
-- after:  [ARITHMETIC_OVERFLOW] overflow. ... SQLSTATE: 22003

SET spark.sql.codegen.wholeStage=false;
SELECT a FROM t WHERE NOT (a > 0 AND b > 0) AND y + 1 > 0;
-- before and after: [ARITHMETIC_OVERFLOW] overflow. ... SQLSTATE: 22003

The same happens in non-ANSI mode with year-month interval arithmetic, and with the aggregate FILTER clause.

Does this PR introduce any user-facing change?

Yes. With whole-stage codegen on, an error raised by a later conjunct on a row where an earlier conjunct is NULL now fails the query, as it already did with codegen off. A row can still be skipped before the filter, for example by Parquet row-group statistics, and then no error is raised.

The later conjuncts also run on more rows than before:

  • a nondeterministic conjunct such as rand(seed) can return different values on the remaining rows;
  • a side-effecting UDF is called on rows that are then dropped;
  • an expensive later conjunct costs more on rows where an earlier, nullable conjunct is NULL.

Once a condition has a conjunct that can be NULL, the IS NOT NULL checks after that conjunct are evaluated in the order of the condition on every row, not only on rows where a conjunct is NULL, so a check written before a conjunct can now raise an error on a row that the conjunct dropped before, as it does with codegen off. Setting spark.sql.legacy.filterShortCircuitOnNullConjunct=true restores the previous behavior. The migration guide has an entry for this.

How was this patch tested?

Six new tests in WholeStageCodegenSuite. Each runs with whole-stage codegen on and off, and with the legacy config on and off; it expects the row to be skipped only with codegen on and the legacy config set, and the error in every other combination:

  • the ANSI reproducer, and a variant with a common y + 1 that takes the CSE path of FilterExec (checked from the generated code, with subexpressionElimination.filterExec.enabled on and off), and a NULL conjunct from OR; without an error, the CSE path drops the row whose condition is NULL;
  • the non-ANSI year-month interval reproducer (INTERVAL_ARITHMETIC_OVERFLOW), and a user-written cast(s AS INT) IS NOT NULL check, which is FALSE on the row, before the NULL conjunct: the row is dropped in every combination;
  • a NULL conjunct followed by a FALSE one, which must not raise; it also checks that no flag is generated when no conjunct can be NULL, or when nothing after the first conjunct that can be NULL can raise, and that it is generated once a conjunct can raise;
  • an IS NOT NULL check on a column that is FALSE on the row and precedes the overflowing conjunct in the condition, inferred or user-written, in the non-CSE and CSE paths of FilterExec and in the aggregate FILTER clause: the row is dropped in every combination. A check written after the overflowing conjunct stays after it, in both paths, so the query still raises;
  • an IS NOT NULL check on cast(s AS INT), which raises on the row, written after a conjunct that contains the expression, in the non-CSE and CSE paths: the row is dropped in every combination when the conjunct is FALSE, and the query raises CAST_INVALID_INPUT when it is TRUE. The same check written before a conjunct that can be NULL raises on a row where that conjunct is TRUE and the next one FALSE, since the checks after the first conjunct that can be NULL are placed in the order of the condition for every row;
  • the aggregate FILTER clause.

The tests use a Parquet table with filter pushdown off, so the filter is neither evaluated on a local relation by the optimizer nor skipped by row-group statistics.

Also ran WholeStageCodegenSuite, SQLQuerySuite, DataFrameSuite, DataFrameAggregateSuite, SubexpressionEliminationSuite, FilterPushdownSuite and SQLQueryTestSuite locally. The only failure is udtf/udtf.sql - Python UDTFs, whose golden output differs from the local Python's ValueError message ('input' is not in list vs list.index(x): x not in list), which is unrelated to this change.

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

Generated-by: Claude Code (Claude Opus 5.5)

…tage codegen of a filter

Whole-stage codegen of a filter condition, and of the FILTER clause of an
aggregate function, dropped a row at the first top-level conjunct that
evaluated to NULL, without evaluating the remaining conjuncts. The
interpreted path evaluates the whole AND with And.eval, which stops only
at FALSE, so an error raised by a later conjunct on such a row was raised
with whole-stage codegen off but not with it on.

Generate a flag that records a NULL conjunct, keep evaluating the
remaining conjuncts, and drop the row after them, so that only a FALSE
conjunct stops the evaluation, as the SQL standard requires. The flag is
generated only when a conjunct can be NULL. The legacy config
spark.sql.legacy.filterShortCircuitOnNullConjunct restores the previous
codegen behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MaxGekk MaxGekk changed the title [SPARK-60315][SQL] Evaluate the conjuncts after a NULL one in whole-stage codegen of a filter [SPARK-60315][SQL] Fix inconsistent filter behavior with whole-stage codegen on and off when a conjunct is NULL Oct 17, 2026
@MaxGekk

MaxGekk commented Oct 17, 2026

Copy link
Copy Markdown
Member Author

cc @cloud-fan @LuciferYang @srielau @dongjoon-hyun @uros-b
This fixes a whole-stage codegen on/off inconsistency in FilterExec and aggregate FILTER. A NULL conjunct short-circuited codegen but not the interpreted path. It touches the FilterExec CSE branch, and the SQL-standard reasoning plus a comparison with 9 other DBMSs are in the description. Could you take a look?

MaxGekk added a commit to vecbricks/varka that referenced this pull request Oct 17, 2026
### What changes were proposed in this pull request?

This updates milestone 7's plan so it says what actually happened before the milestone closes. Only plan documents change.

* **Marked done, with how they ended:**
  * the comment rewrite (#907);
  * the post on how Spark compiles a query, published on 17 October;
  * both halves of checking kernels as C2 compiled them;
  * the last two benchmark ports to Java (#900);
  * the filter-order fix (#908).
* **Scored against live CI runs:**
  * **The CI rework.** Its last four tests: three pass, and one, the `fix` label check, can't be observed until a pull request carries that label.
  * **Error Prone and NullAway on every pull request.** The step takes 39 to 45 s in a Spark run and 157 s in a run that touches Varka's Java. The plan predicted 2.5 and 10 minutes.
  * **The engine's Maven cache.** It works on host runners: the cache is restored and the install runs offline with no download.
* **Moved to milestone 8:**
  * **Promotion,** a cadence rather than a closable task, as it came in from milestone 6.
  * **The NULL-conjunct filter disagreement.** Spark's own answer is under review upstream: SPARK-60315 and apache#59573 propose that codegen raise as the interpreted path does. Fixing Varka to today's default would be undone by that change. Because of this, the nightly fuzzing of nested queries stays off for now.
* **The live runs found three small CI defects. They join the closing task's debt sweep:**
  * a scoped push still runs `admit` and `Precompile Spark` when the precondition reports `pyspark-periodic`, which cost one run a 67-minute wait;
  * the check sync re-sends an unchanged status on every pass while a run is rerun;
  * the container jobs restore the engine cache to `/github/home/.m2` while Maven reads `/root/.m2/repository`, so they still download plugins.
* **Two test findings from the mutation work** join the sweep too: an option-matrix test failing under two settings, and a noisy plan-size test.

### Why are the changes needed?

The milestone closes by reading the plan row by row against what it promised. Without these updates the plan would show finished work as in progress, give no answer for the predictions about CI, and leave the defects the live runs found unrecorded.

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

No. Plan documents only.

### How was this patch tested?

* The issue mirror's row classifier (`dev/varka_issues.py`, its doctests) reads every changed row as intended: the done rows as done, the two moved rows as moved, and the two rows added to milestone 8 as open.
* The pre-commit check passes.
* Every number comes from a named run or job on GitHub's runners; the plan cites each one.

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

Generated-by: Claude Code (Claude Opus 5.5)
@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Contributor

Not a committer, just read through this one closely and built it at 69318f692f3. The fix reads correct to me. Two small notes.

In "We considered the opposite fix ...", the closing "That path is kept available through the legacy config" reads as if the config gives the skip-at-NULL semantics that fix would have, but it only changes generated code: with it set the row is skipped with codegen on, while codegen off still raises. The precise version is in the first section ("The interpreted path is unchanged in both modes"), so this is only about that one sentence, which would carry into the commit message.

On "Join conditions ... are not changed": an inner join pushes the single-side conjuncts into a Filter, so I checked this with a left outer join, where the condition stays on the join, and the legacy config makes no difference there. Matches what you describe.

@cloud-fan cloud-fan 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.

Review summary

The PR changes the stop rule at the right place. With whole-stage codegen on, a NULL conjunct now sets a flag instead of ending the row's evaluation, which matches And.eval, and the legacy config regenerates exactly the old code. One ordering interaction remains. generatePredicateCode and the CSE branch of FilterExec.doConsume still emit plain-column IsNotNull checks lazily, but codegen off evaluates them first, because InferFiltersFromConstraints prepends them. So after a NULL conjunct, codegen can now raise from a later conjunct on a row that codegen off drops at a FALSE isnotnull. That is a new codegen-only failure on queries that succeeded in both modes before. A user-written guard written first, including in an aggregate FILTER clause, hits the same failure. Any fix should keep each check's position in the condition. An IsNotNull written after the raising conjunct must stay after it, or that shape goes back to the original inconsistency. Separately, the new tests never check that the CSE branch drops a row whose condition is NULL: the only CSE query overflows before the trailing flag check. The extra evaluation of later conjuncts on NULL rows is a cost that the PR description and the migration guide explicitly accept, so it is not raised as a finding.

Cross-cutting observations

  • The FilterExec CSE branch repeats the IsNotNull and conjunct interleaving of generatePredicateCode by hand, so the IsNotNull ordering fix has to be made in both places. Today no test checks that the CSE branch drops a NULL-condition row, so a mistake made there while fixing the ordering would go unnoticed; adding that CSE-path test first gives the ordering fix a safety net.
    Separation: The ordering fix and the missing CSE drop test close independently with different invariants: one decides when plain-column IsNotNull checks run, and the other only adds a failure signal for the existing trailing flag check. Neither changes the other's repair, scope, or severity.

Findings

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

Non-blocking (P2)

  • Codegen can now raise past a deferred IsNotNull that codegen off checks first — sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:180 — see inline.

Nit (P3)

  • No test checks that the FilterExec CSE branch drops a NULL-condition row — sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:2921 — see inline.

PR description suggestions

  • In the paragraph starting "We considered the opposite fix", replace "That path is kept available through the legacy config." with "Setting spark.sql.legacy.filterShortCircuitOnNullConjunct to true only restores the previous whole-stage codegen behavior; with whole-stage codegen off, the query still raises."

@cloud-fan

Copy link
Copy Markdown
Contributor

Thanks for the detailed write-up and the cross-engine comparison. The stop rule now matches And.eval, but I think the flag interacts badly with the deferred IsNotNull checks. Both codegen branches emit an IsNotNull just before the first conjunct that references its column, or after all conjuncts. With codegen off, the condition is evaluated in order, and the IsNotNull predicates that InferFiltersFromConstraints prepends come first. Take WHERE NOT (a > 0 AND b > 0) AND y + 1 > 0 AND x > 0 on a row with a NULL, b = 1, y = Int.MaxValue, x NULL. Codegen off drops the row at isnotnull(x). With this PR, codegen sets the flag, evaluates y + 1, and fails with ARITHMETIC_OVERFLOW. Before the PR, both modes returned without an error. A user-written guard written first has the same problem: in WHERE x IS NOT NULL AND NOT (a > 0 AND b > 0) AND y + 1 > 0, isnotnull(x) is emitted after all the other conjuncts. One way to fix it: once a flag is in play, emit each pending attribute-only IsNotNull check just before the first later conjunct it precedes in the condition. A check written after the overflowing conjunct, as in ... AND y + 1 > 0 AND x IS NOT NULL, then stays where it is, and that query still raises in both modes. Hoisting all pending checks right after the NULL conjunct would drop that row with codegen on and bring back the original inconsistency for that shape. What do you think?

@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

The deferred IsNotNull ordering regression and missing CSE NULL-drop assertion remain unresolved in their existing inline discussions. The ordering interaction can make previously successful queries fail only with whole-stage codegen enabled. The test gap leaves the CSE branch's final NULL rejection without a result-level failure signal. A separate small issue is duplicate predicate binding in the non-CSE helper, which adds avoidable driver generation work, including in legacy mode. Additional suffix evaluation after NULL is an explicitly accepted effect of the change.

Cross-cutting observations

  • The guard-ordering repair changes both manually mirrored emitters, while the current tests cannot detect a missing final NULL rejection in the CSE branch. Establishing the nonthrowing CSE result assertion gives that repair a useful safety net.
    Separation: Ordering decides when a FALSE guard stops evaluation; the result assertion detects eventual rejection after NULL. Neither repair necessarily closes the other, and their owners, scope, and non-blocking severity remain independent.

Findings

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

Non-blocking (P2)

  • NULL continuation can raise before an earlier FALSE IsNotNull guard — sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:180 — unresolved in existing discussion.

Nit (P3)

  • The CSE final NULL rejection has no result-level regression assertion — sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:2921 — unresolved in existing discussion.
  • Reuse the predicates bound for NULL-flag eligibility — sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:207 — see inline.

Existing discussions

Verification

  • Review judgments were checked against the pinned patches and surrounding source. No tests or benchmarks were executed in this worker.

PR description suggestions

  • In the paragraph beginning "We considered the opposite fix", replace "That path is kept available through the legacy config." with "Setting spark.sql.legacy.filterShortCircuitOnNullConjunct to true restores only the previous whole-stage codegen behavior; with whole-stage codegen disabled, the query still raises."

@spark-test

Copy link
Copy Markdown
Collaborator

The current source confirms this interaction: both generators defer plain-column IsNotNull checks while NULL now falls through. Preserving each guard's original condition position when a NULL flag is active would address the reported new codegen-only failure; a guard written after the overflowing conjunct must stay after it. Both the shared aggregate helper path and FilterExec CSE branch need the same treatment.

@spark-test

Copy link
Copy Markdown
Collaborator

The AI review requested by @HyukjinKwon finished.

Generated by Omnigent on Databricks

… conjunct after one that can be NULL

Address the review:
- With the NULL-conjunct flag, once a conjunct that can be NULL is generated,
  generate the IsNotNull checks that precede a later conjunct in the condition
  before it, in both predicate codegen paths, so that a FALSE check drops the
  row before an error the conjunct raises, as with whole-stage codegen off.
- Bind the other conjuncts once in generatePredicateCode.
- Test that the CSE path drops a row whose condition is NULL, and add the
  IsNotNull ordering tests for both paths, a check on an expression, a NULL
  conjunct from OR, and the aggregate FILTER clause.
- Make the migration guide entry precise about the evaluation order.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@MaxGekk

MaxGekk commented Oct 19, 2026

Copy link
Copy Markdown
Member Author

Thanks @cloud-fan, confirmed and fixed in 3264b00. There is also a pre-existing variant of it without a NULL conjunct, now SPARK-60329; the repro matrix and the details are in the inline thread.

@MaxGekk

MaxGekk commented Oct 19, 2026

Copy link
Copy Markdown
Member Author

Thanks for the careful read and for checking the outer join case. You are right about that sentence: the legacy config only restores the previous whole-stage codegen behavior, and codegen off still raises. I reworded it in the PR description, which the merge script uses as the commit message, so the commit will carry the corrected version.

@uros-b

uros-b commented Oct 19, 2026

Copy link
Copy Markdown
Member

Thank you @MaxGekk and @cloud-fan!

@cloud-fan cloud-fan 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.

Review summary

Since the last review at 69318f6, 3264b00 fixes both earlier findings. After a nullable conjunct, the IS NOT NULL checks written before each later conjunct are now generated before it in both emitters. So the inferred check, a guard written first, and the aggregate FILTER guard drop the row as they do with codegen off, and a check written after the overflowing conjunct still raises. The CSE path's final NULL-flag check now has a result-level test on the non-overflowing table. The double binding of the other conjuncts is also gone.

One codegen-only failure remains after a NULL conjunct. The SPARK-51356 nested branch still generates a later-written IS NOT NULL(expr) before the conjunct that contains expr, so the query can raise where codegen off returns no rows. This was already present at 69318f6. LuciferYang's thread on basicPhysicalOperators.scala covers it, and the author has agreed to gate the branch in both emitters and add a test.

The rest are nits. The migration guide and the precedingNotNullChecks scaladoc promise condition-order evaluation, which the per-reference placement does not give for a check written after a conjunct that references its column. A test comment attributes eager common-subexpression evaluation to the interpreted predicate instead of GeneratePredicate. And outputAttrs is now an unused parameter of the 9-argument generatePredicateCode.

Cross-cutting observations

  • Both remaining departures from condition order after a NULL conjunct come from an IS NOT NULL check written after a conjunct but generated before it because that conjunct contains or references the check's operand. When the operand is a complex expression, codegen raises an error that codegen off never reaches, and the nested branch should stop hoisting such checks in both emitters. When it is a plain column, codegen only drops a row that codegen off would fail on, and the tightened-nullability binding requires that placement. So once the nested case is fixed, the migration guide and scaladoc should present it as the one remaining exception.
    Separation: The complex-expression case is a runtime regression closed by gating one branch, while the plain-column case matches the merge target at runtime and its only PR-caused defect is the new documentation guarantee. The two repairs touch different surfaces and neither depends on the other in code; the documentation only needs to describe the behavior that ships.

Findings

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

Non-blocking (P2)

  • The nested IS NOT NULL branch can raise after a NULL conjunct where codegen off returns no rows — sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:326 — unresolved in existing discussion.

Nit (P3)

  • The migration guide promises condition-order evaluation that per-reference IS NOT NULL placement does not give — docs/sql-migration-guide.md:54 — see inline.
  • Test comment attributes eager CSE to the interpreted predicate — sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:2973 — see inline.
  • outputAttrs is now an unused parameter of the 9-argument generatePredicateCode — sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:252 — see inline.

Re-review status

Prior AI findings: 2 addressed, 0 still present; additional unresolved findings in this review: 4.

New attribution: 3 newly introduced, 1 late catch, 0 previously raised, 0 unattributed.

Remaining prior AI findings

No prior AI findings remain.

Existing discussions

Verification

  • Both findings of the review at 69318f6 are fixed at 3264b00: the preceding IS NOT NULL checks are generated before each conjunct after the first nullable one in both emitters, and the CSE query is checked on the non-overflowing table.
  • The nested-branch failure is a late catch: at 69318f6 the NULL-conjunct flag and the SPARK-51356 nested branch already coexisted in both emitters.

PR description suggestions

  • In the first paragraph, "codegen evaluates the conjuncts after a NULL one in the order of the condition" overstates in the same way as the migration guide. An IS NOT NULL check on a column that a later conjunct references is still generated just before that conjunct, even when it is written after it. Since this text becomes the commit message, consider "codegen keeps evaluating the conjuncts after a NULL one" there.

Comment thread docs/sql-migration-guide.md Resolved
…the conjunct it follows, after a NULL conjunct

After a conjunct that can be NULL, the nested IsNotNull check on an expression
(SPARK-51356) that is written after the conjunct containing the expression is no
longer generated before that conjunct, in `generatePredicateCode` and the CSE
branch of `FilterExec.doConsume`, so that it does not raise an error on a row the
conjunct drops as FALSE, as with codegen off. Add a test for this shape.

Drop the unused `outputAttrs` parameter of `generatePredicateCode`, fix a test
comment about which predicate evaluates common subexpressions first, and list the
IS NOT NULL check on a referenced column as the exception to the condition order
in the migration guide and the `precedingNotNullChecks` scaladoc.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

@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 reviewed the latest commit, 1fce024, and left 13 inline comments. Here is a summary, ordered by priority.

Correctness

  1. GeneratePredicateHelper L305: afterNullable is decided at codegen time, so the moved checks and the skipped nested checks also change results on rows where no conjunct is NULL, in both directions; the migration guide, the legacy config doc and the PR description cover only rows where a conjunct is NULL, and the SPARK-60377 example in the description no longer reproduces with the default config.

Performance

  1. GeneratePredicateHelper L185: the flag and the hoisted checks are generated whenever a conjunct can be NULL, even when nothing after it can raise, and the hoisted checks decode their columns on every row; gating both with ExprUtils.canEvaluateUnconditionally keeps master's code for such filters.

Docs and comments

  1. sql-migration-guide.md L54: "The one exception" is narrower than the code (checks on expressions through synthetic column checks, the conjuncts up to the check's own position, and the nested hoisting at the first nullable conjunct).
  2. sql-migration-guide.md L54: with codegen off, GeneratePredicate evaluates common subexpressions before the condition, so the parity sentence does not hold when the conjuncts after a FALSE one share a subexpression.
  3. FilterExec L603: the comment on boundOtherPreds (L381-383) still describes it as used only by the CSE path.

Tests

  1. WholeStageCodegenSuite L3003: only cseQuery runs the preceding checks through the CSE branch; the check written after the overflowing conjunct and the inferred check never do.
  2. WholeStageCodegenSuite L2961: the "no flag" assertion passes vacuously without a whole-stage codegen subtree.
  3. WholeStageCodegenSuite L2821: the second row fails more conditions than b < 0.

Cleanup

  1. FilterExec L516: passing nullFlag for the IsNotNull checks makes their "defensive" NULL branch set the flag and fall through instead of dropping the row.
  2. GeneratePredicateHelper L320: a check hoisted by precedingNotNullChecks is followed by a redundant synthetic IsNotNull on the same column.
  3. FilterExec L533: the withSubExprEliminationExprs(Map.empty) block is now duplicated.

Follow-ups

  1. AggregateCodegenSupport.scala:237 (on the aggregate FILTER test, WholeStageCodegenSuite L3078): pre-existing, the common subexpressions of the update expressions are evaluated before each FILTER, so avg(y + 1) FILTER (WHERE b < 0) raises only with codegen on.
  2. GeneratePredicateHelper L297: the ordering is mirrored by hand in two emitters; computing it once would make SPARK-60329 and SPARK-60377 one edit each.

Items 1 and 2 are the most important. Item 1 only needs the docs and the PR description, which becomes the commit message. Items 12 and 13 are follow-ups and do not need to block this PR.

Comment thread docs/sql-migration-guide.md Resolved
Comment thread docs/sql-migration-guide.md Resolved
…checks only when a conjunct or check can raise

Generate the flag only when a conjunct after the first one that can be NULL, or
an IsNotNull check, cannot be evaluated unconditionally, and generate the pending
checks before a conjunct only when it or one of them cannot, so that common
`OR`/`IN` filters keep the generated code of master. Do not pass the flag to the
IsNotNull checks, so they keep dropping the row. Skip the redundant synthetic
check for a column whose check `precedingNotNullChecks` generated. Move the
CSE-free check generation into `genNotNullWithoutCSE`.

Document that the placement is decided at code generation, so the checks after a
conjunct that can be NULL are evaluated in the order of the condition on every
row, and describe the exception to the order more broadly. Pin the first-written
check and the CSE path in the tests, and make the no-flag assertion fail when the
filter is not in whole-stage codegen.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

@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 items 1-13, @MaxGekk. I reviewed the latest commit, f81f1c8, and left 2 inline comments, continuing the numbering from items 1-13.

Before merging: the PR description

  1. WholeStageCodegenSuite L2822: the reproducer in "Why are the changes needed?" leaves Parquet filter pushdown on, so in a default multi-core session the first row's file is skipped by row-group statistics and both modes return 0.
  2. GeneratePredicateHelper L177: "GeneratePredicateHelper gets three helpers" is out of date; the trait now gets six, including mayRaise, which the description does not name.

+1, LGTM. CI is green on f81f1c8. Items 14 and 15 only need the PR description, which becomes the commit message, so could you update it before merging?

@MaxGekk

MaxGekk commented Oct 21, 2026

Copy link
Copy Markdown
Member Author

Thanks @dongjoon-hyun, the PR description is updated for items 14 and 15. I merged master to resolve the conflict in WholeStageCodegenSuite with the SPARK-60403 tests; the suite passes locally with both sets of tests.

@cloud-fan @LuciferYang your threads are answered in 1fce024 and f81f1c8: the preceding checks are placed in the order of the condition after a nullable conjunct, the nested check on an expression stays at its position, and the flag and the hoisting are generated only when a conjunct or check can raise. Could you take another look? If there are no further comments, I plan to merge once CI is green.

@MaxGekk

MaxGekk commented Oct 22, 2026

Copy link
Copy Markdown
Member Author

Merging to master/4.x. Thank you, @cloud-fan @dongjoon-hyun @LuciferYang @uros-b @HyukjinKwon @SEPURI-SAI-KRISHNA for review.

@MaxGekk MaxGekk closed this in 930c571 Oct 22, 2026
MaxGekk added a commit that referenced this pull request Oct 22, 2026
…codegen on and off when a conjunct is NULL

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

This PR fixes inconsistent behavior of a filter between whole-stage codegen on and off: when an earlier conjunct of the condition is NULL on a row and a later one raises an error on that row, the query failed with codegen off but returned rows with codegen on. After this PR, codegen keeps evaluating the conjuncts after a NULL one, so it raises the error in that case too. An `IS NOT NULL` check that precedes the raising conjunct in the condition still drops the row first in both modes.

Whole-stage codegen of a filter condition (`FilterExec`) and of the `FILTER` clause of an aggregate function (`AggregateCodegenSupport`) generates each top-level conjunct separately and drops the row as soon as one of them is FALSE **or NULL** (`if (isNull || !value) continue;`). The interpreted path evaluates the whole condition with `And.eval`, which stops only at FALSE. So when an earlier conjunct is NULL and a later one raises on that row, the query fails with codegen off and returns rows with it on.

This PR changes the generated code so that only a FALSE conjunct stops the evaluation:

- `GeneratePredicateHelper` gets six helpers: `splitNotNullPreds` (splits the condition into the `IsNotNull` checks and the other conjuncts, keeping the number of checks that precede each conjunct), `mayRaise` (whether an expression can raise an error, is nondeterministic or may have side effects, via `ExprUtils.canEvaluateUnconditionally`), `nullConjunctFlag` (a fresh flag name, or `None`), `conjunctCheck` (the per-conjunct check), `withNullConjunctFlag` (declares the flag before the checks and drops the row after them if it is set) and `precedingNotNullChecks` (the pending checks to generate before a conjunct).
- A NULL conjunct sets the flag, and the remaining conjuncts are still evaluated: `if (isNull) { flag = true; } else if (!value) continue;`. The row is dropped after all of them: `if (flag) continue;`.
- The flag is generated only when some conjunct can be NULL after binding, and a conjunct after the first such one, or one of the `IsNotNull` checks, can raise an error, is nondeterministic or may have side effects (`ExprUtils.canEvaluateUnconditionally`). Otherwise the evaluation after a NULL conjunct is not observable and the generated code is unchanged, e.g. for `WHERE (a > 5 OR b > 5) AND c = 1 AND d = 2`. The `IsNotNull` checks are never NULL and keep their early `continue`, so the tightened-nullability binding of the later conjuncts, and of the CSE precomputes, stays safe.
- With the flag, once a conjunct that can be NULL has been generated, the `IsNotNull` checks that precede a later conjunct in the condition are generated before it when the conjunct or one of the checks can raise, as `And.eval` evaluates them, instead of lazily before the first conjunct that references their column. So a FALSE check drops the row before an error the later conjunct raises on it, as with codegen off (`splitNotNullPreds` keeps the number of checks that precede each conjunct, `precedingNotNullChecks` returns the pending ones). The conjuncts before the first one that can be NULL are never reached after a NULL conjunct, so the checks before them keep the lazy placement, and without the flag the generated code is unchanged. The placement is decided at code generation, so once a condition has a conjunct that can be NULL, the checks after it are evaluated in the order of the condition on every row, not only on rows where a conjunct is NULL; a row with no NULL conjunct can then change too, in both directions, always toward the codegen-off result.
- With the flag, after a conjunct that can be NULL, an `IS NOT NULL` check on an expression (SPARK-51356) that is written after the conjunct containing the expression is no longer generated before that conjunct. It stays at its position, as `And.eval` evaluates it, so it does not raise an error on a row that the conjunct drops as FALSE.
- Both code paths are changed: `generatePredicateCode`, which the aggregate `FILTER` clause also uses, and the CSE branch of `FilterExec.doConsume`, which the code comments require to stay in step with it.
- New legacy config `spark.sql.legacy.filterShortCircuitOnNullConjunct` (internal, default `false`, version 4.4.0). Set to `true`, it restores the previous codegen behavior. The interpreted path is unchanged in both modes.

Join conditions and `MergeRowsExec` generate the whole condition through `And.doGenCode`, which already evaluates the right side after a NULL left side, so they are not changed.

Not fixed here, on master as well as after this PR:
- With whole-stage codegen on, an `IS NOT NULL` check on a column is generated just before the first conjunct that references the column, so `WHERE x IS NOT NULL AND y + 1 > 0 AND x > 0` raises `ARITHMETIC_OVERFLOW` with codegen on and drops the row with codegen off. That is tracked in SPARK-60329. The check is also generated before that conjunct when it is written after it, and so before the conjuncts between that one and its own position, and a check on an expression over the column does the same through a synthetic check on the column. So after a NULL conjunct the evaluation can still drop the row where codegen off raises; the migration guide entry lists this as the exception to the order of the condition.
- Before the first conjunct that can be NULL, including that conjunct itself, or with the legacy config, an `IS NOT NULL` check on an expression is still generated before the first conjunct that contains the expression, even when it is written after it, so `WHERE coalesce(b, cast(s AS INT)) < 0 AND cast(s AS INT) IS NOT NULL` raises `CAST_INVALID_INPUT` with codegen on and drops the row with codegen off on `(b, s) = (1, 'x')`. That is tracked in SPARK-60377.
- With whole-stage codegen off, `GeneratePredicate` evaluates a subexpression shared by several conjuncts before the condition, so `WHERE NOT (a > 0 AND b > 0) AND b < 0 AND y + 1 > 0 AND y + 1 > -1` raises `ARITHMETIC_OVERFLOW` with codegen off and returns no rows with codegen on, where the FALSE `b < 0` stops the evaluation. That is tracked in SPARK-60392.
- Whole-stage codegen evaluates the common subexpressions of the update expressions of an aggregate function before its `FILTER` clause, so `SELECT avg(y + 1) FILTER (WHERE b < 0) FROM t` raises `ARITHMETIC_OVERFLOW` with codegen on and returns NULL with codegen off. That is tracked in SPARK-60393.
- The interleaving of the checks and the conjuncts is mirrored by hand in `generatePredicateCode` and in the CSE branch of `FilterExec.doConsume`. SPARK-60394 is to compute it once for both.

#### SQL standard

- 7.11 `<where clause>`, GR 2 (and 10.9 `<aggregate function>`, GR 4a, for `<filter clause>`): the search condition is effectively evaluated for each row, and the result keeps the rows for which it is True.
- 6.35 `<boolean value expression>`, Table 11: Unknown AND True is Unknown, Unknown AND False is False. After an Unknown conjunct the result of the search condition still depends on the remaining ones.
- 9075-1 "Rule evaluation order" (SQL-92 3.3.4.4): only the *inessential* parts, those not needed to determine the result of the expression or search condition, may be skipped, and whether their exceptions are raised is implementation-dependent. After a NULL conjunct the rest is essential. The order of evaluation is implementation-dependent too, but in every order the raising conjunct is either evaluated first or is still essential, so the exception is raised. Only a FALSE conjunct makes the rest inessential.

#### Other DBMSes

Table `t(a INT, b INT, y)` with rows `(NULL, 1, <raises>)` and `(0, 1, <ok>)`. `<E>` raises on the first row:
- `y + 1 > 0` with `y` at the maximum of its type: `INT`, or `BIGINT` on MySQL and MariaDB, which widen `INT + INT`;
- `10 / y > 0` with `y = 0` on Oracle, whose `NUMBER` does not overflow at 32 bits;
- `abs(y) > 0` with `y` at the minimum `BIGINT` on SQLite, where `+` switches to floating point.

The images and credentials are those of `connector/docker-integration-tests`.

| Query | PostgreSQL 18.2 | MySQL 9.6.0 | MariaDB 12.2.2 | SQL Server 2022 | Oracle Free 23.26 | DB2 11.5.9 | H2 2.3.232 | Derby 10.16 | SQLite 3.46 |
|---|---|---|---|---|---|---|---|---|---|
| `WHERE NOT (a > 0 AND b > 0) AND <E>` | skip | skip | skip | **raise** | skip | **raise** | **raise** | skip | skip |
| `WHERE <E> AND NOT (a > 0 AND b > 0)` | raise | raise | raise | raise | **skip** | raise | raise | **skip** | raise |
| `WHERE a > 0 AND <E>` | skip | skip | skip | skip | skip | **raise** | **raise** | skip | skip |
| `WHERE b < 0 AND <E>` (FALSE first) | - | - | - | - | - | raise | - | - | - |
| `count(a) FILTER (WHERE NOT (a > 0 AND b > 0) AND <E>)` | **raise** | n/a | n/a | n/a | **raise** | n/a | **raise** | n/a | skip |

"-" means no error and an empty result; "n/a" means the `FILTER` clause is not supported.

- In WHERE, most engines drop the row at the NULL conjunct. Oracle and Derby do it even when the raising conjunct is written first, so they reorder.
- DB2 and H2 raise. SQL Server raises for the JIRA's shape but not for a plain `a > 0` first.
- For the aggregate `FILTER` clause, PostgreSQL, Oracle and H2 evaluate the whole `AND` and raise, as this PR does.

We considered the opposite fix: make the interpreted path stop at the first NULL conjunct too. It matches most engines' WHERE behavior, but it departs from the standard's text and from what Spark already does with codegen off. Setting `spark.sql.legacy.filterShortCircuitOnNullConjunct` to `true` only restores the previous whole-stage codegen behavior; with whole-stage codegen off, the query still raises.

### Why are the changes needed?

The same query must not raise with whole-stage codegen off and return rows with it on (SPARK-60315). Reproducer (ANSI mode):

```sql
CREATE TABLE t USING parquet AS
  SELECT * FROM VALUES (NULL, 1, 2147483647), (0, 1, 0) AS v(a, b, y);
-- The rows can be written to different files, and `NOT (a > 0 AND b > 0)` is pushed down as
-- `a <= 0 OR b <= 0`, which skips the first row's file by its statistics.
SET spark.sql.parquet.filterPushdown=false;

SET spark.sql.codegen.wholeStage=true;
SELECT a FROM t WHERE NOT (a > 0 AND b > 0) AND y + 1 > 0;
-- before: 0
-- after:  [ARITHMETIC_OVERFLOW] overflow. ... SQLSTATE: 22003

SET spark.sql.codegen.wholeStage=false;
SELECT a FROM t WHERE NOT (a > 0 AND b > 0) AND y + 1 > 0;
-- before and after: [ARITHMETIC_OVERFLOW] overflow. ... SQLSTATE: 22003
```

The same happens in non-ANSI mode with year-month interval arithmetic, and with the aggregate `FILTER` clause.

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

Yes. With whole-stage codegen on, an error raised by a later conjunct on a row where an earlier conjunct is NULL now fails the query, as it already did with codegen off. A row can still be skipped before the filter, for example by Parquet row-group statistics, and then no error is raised.

The later conjuncts also run on more rows than before:
- a nondeterministic conjunct such as `rand(seed)` can return different values on the remaining rows;
- a side-effecting UDF is called on rows that are then dropped;
- an expensive later conjunct costs more on rows where an earlier, nullable conjunct is NULL.

Once a condition has a conjunct that can be NULL, the `IS NOT NULL` checks after that conjunct are evaluated in the order of the condition on every row, not only on rows where a conjunct is NULL, so a check written before a conjunct can now raise an error on a row that the conjunct dropped before, as it does with codegen off. Setting `spark.sql.legacy.filterShortCircuitOnNullConjunct=true` restores the previous behavior. The migration guide has an entry for this.

### How was this patch tested?

Six new tests in `WholeStageCodegenSuite`. Each runs with whole-stage codegen on and off, and with the legacy config on and off; it expects the row to be skipped only with codegen on and the legacy config set, and the error in every other combination:

- the ANSI reproducer, and a variant with a common `y + 1` that takes the CSE path of `FilterExec` (checked from the generated code, with `subexpressionElimination.filterExec.enabled` on and off), and a NULL conjunct from `OR`; without an error, the CSE path drops the row whose condition is NULL;
- the non-ANSI year-month interval reproducer (`INTERVAL_ARITHMETIC_OVERFLOW`), and a user-written `cast(s AS INT) IS NOT NULL` check, which is FALSE on the row, before the NULL conjunct: the row is dropped in every combination;
- a NULL conjunct followed by a FALSE one, which must not raise; it also checks that no flag is generated when no conjunct can be NULL, or when nothing after the first conjunct that can be NULL can raise, and that it is generated once a conjunct can raise;
- an `IS NOT NULL` check on a column that is FALSE on the row and precedes the overflowing conjunct in the condition, inferred or user-written, in the non-CSE and CSE paths of `FilterExec` and in the aggregate `FILTER` clause: the row is dropped in every combination. A check written after the overflowing conjunct stays after it, in both paths, so the query still raises;
- an `IS NOT NULL` check on `cast(s AS INT)`, which raises on the row, written after a conjunct that contains the expression, in the non-CSE and CSE paths: the row is dropped in every combination when the conjunct is FALSE, and the query raises `CAST_INVALID_INPUT` when it is TRUE. The same check written before a conjunct that can be NULL raises on a row where that conjunct is TRUE and the next one FALSE, since the checks after the first conjunct that can be NULL are placed in the order of the condition for every row;
- the aggregate `FILTER` clause.

The tests use a Parquet table with filter pushdown off, so the filter is neither evaluated on a local relation by the optimizer nor skipped by row-group statistics.

Also ran `WholeStageCodegenSuite`, `SQLQuerySuite`, `DataFrameSuite`, `DataFrameAggregateSuite`, `SubexpressionEliminationSuite`, `FilterPushdownSuite` and `SQLQueryTestSuite` locally. The only failure is `udtf/udtf.sql - Python UDTFs`, whose golden output differs from the local Python's `ValueError` message (`'input' is not in list` vs `list.index(x): x not in list`), which is unrelated to this change.

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

Generated-by: Claude Code (Claude Opus 5.5)

Closes #59573 from MaxGekk/SPARK-60315-filter-null-conjunct.

Authored-by: Max Gekk <max.gekk@gmail.com>
Signed-off-by: Max Gekk <max.gekk@gmail.com>
(cherry picked from commit 930c571)
Signed-off-by: Max Gekk <max.gekk@gmail.com>
@MaxGekk

MaxGekk commented Oct 22, 2026

Copy link
Copy Markdown
Member Author

Merge Summary:

Posted by merge_spark_pr.py

MaxGekk added a commit to vecbricks/varka that referenced this pull request Nov 1, 2026
### What changes were proposed in this pull request?

This PR plans three of the milestone's unplanned rows and adds four new ones. It changes plan files only.

**Planned:**
- **A filter whose NULL conjunct comes before one that raises** (medium). Spark's default session returns such a row, because its generated filter stops at the NULL conjunct, while the interpreted filter and Varka raise. Upstream has merged its fix, apache#59573, behind a legacy flag, after Varka's last upstream sync. The plan syncs upstream first, in its own pull request, then rebuilds Varka's conjunct-order rule on top of it: the filter's fallback reads the flag, and the planner holds each fused conjunct to every order a session can use, so EXPLAIN does not depend on a setting.
- **The weekly option matrix on the fork** (small). The run's guard and its failure report move to the fork. It reuses the fork's master Build, re-dispatching that Build when its artifacts have expired. A wait step holds the run until no pull request's matrix or upstream Build is running, and skips the week with a warning after five hours. It takes the slots it finds free.
- **A compile outside every reach window is reported** (small). A warning names the suite and the call site, once per pair. Each JVM writes its own reach file, so one stray compile can no longer turn off test skipping for a whole module.

**Added:**
- **The scalar form of a 128-bit decimal for x86 hosts at two long lanes.** There the de-interleaved pair runs the Vector API's Java fallback, at 44 to 236 ns a row against the scalar loop's 0.7 to 14 in the spike's committed EPYC results.
- **The ghost fallback evaluates every common subexpression up front.** Whole-stage codegen evaluates each one where it is first needed, so a filter that Spark's default session answers raises under Varka. The finding comes from an unmerged branch and had no row.
- **A filter's fusable conjunct that declined behind a cast.** `WHERE CAST(a AS INT) IN (0, 2147483647) AND date_add(d, i) > DATE'2000-01-01'` fused no conjunct, though a projection fuses `date_add(d, i)` over the same table. The row finds whether the conjunct order, the column offset or the filter compiler's admission declines it, and fixes it or records why.
- **Floating-lane filters at two lanes on x86.** The two-lane refusal covers kernels driven at the long lane only, while a floating filter fuses on the DOUBLE lane, whose 128-bit species also has two lanes. The row measures floating filters at 128 bits on x86 and declines those slower than the row path.

**Added to m9's scope:** item 127, choosing each CPU-dependent form (the division form, and the two-lane refusals) on the executor that runs the kernel instead of the driver, for clusters whose driver and executors differ in vector width.

The owner's answers given today are recorded in the plans: the sync and the fix merge separately on the same day; the conjunct-order row is medium; a weekly that runs out of time skips the week; vecbricks/varka's own copy of the weekly stays disabled. Each plan lists its remaining questions with a recommendation.

### Why are the changes needed?

Two of the planned rows fix wrong answers against Spark's default session, the conjunct order and the hoisted subexpressions. The weekly matrix is the only run that covers every option configuration on master, and it has been off on vecbricks/varka since 29 October. The reach report keeps the option matrix's test skipping from being silently disabled.

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

No. Plan files only.

### How was this patch tested?

- The plan lint and the quote check are clean, as are the pre-commit hooks.
- A `/code-review high` of the plans found, and this branch fixes: a failed weekly on the fork reporting to nobody; a wait step that would wait on its own run; a slot formula that subtracted jobs which never run beside the bins; a warning key that would hide every suite after the first; a renamed reach file that the matrix would no longer find; and three misattributed citations.

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

Generated-by: Claude Code (Opus 5.5)
MaxGekk pushed a commit to MaxGekk/spark that referenced this pull request Nov 9, 2026
SPARK-60315 (apache#59573), which this sync brings in, makes whole-stage
codegen evaluate the conjuncts after a NULL one, so Spark's default session
raises INTERVAL_ARITHMETIC_OVERFLOW on the reproducer
varka-386-20261017-22897.sql as Varka does. VarkaSparkReproducerSuite fails a
reproducer marked known that now agrees, so the file is marked a regression,
and the README line that named its status is updated with it.

Generated-by: Claude Code (claude-opus-5-5)
MaxGekk added a commit to vecbricks/varka that referenced this pull request Nov 20, 2026
…oes (#1556)

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

Varka fuses the conjuncts of a filter it can compile into a vector kernel and leaves the others in a row `FilterExec` above its node; a batch the kernel cannot serve is filtered row by row by a per-row fallback over the whole condition. Both halves have to raise, or answer, as Spark's own filter does. SPARK-60315 (apache#59573, on Varka's master since the last upstream sync) changed what that is:

- Spark's filter no longer stops at a NULL conjunct in whole-stage codegen: like the interpreted `And`, it goes on to the later conjuncts, and only a FALSE one stops it. So a later conjunct that raises on the row raises. The internal conf `spark.sql.legacy.filterShortCircuitOnNullConjunct` restores the old codegen behaviour.
- Codegen's placement of the `IS NOT NULL` checks changed with it. Once a conjunct that can be NULL has run, the checks written before a later conjunct are generated ahead of it in written order (`precedingNotNullChecks`), when it or one of them may raise; a column check is not added where the column has its own check; and the check of a larger expression written after the conjunct containing it is left to the end. All of this happens only when some conjunct can be NULL and a later conjunct or a check may raise (`nullConjunctFlag`).

This PR makes Varka follow both:

1. **`VarkaConjunctOrder.codegenOrder(conjuncts, childOutput, legacy)`** ports the merged `generatePredicateCode`, with the flag computed as Spark computes it: nullability bound over the child's output with the checked columns non-nullable, and `mayRaise` as Spark's own `!ExprUtils.canEvaluateUnconditionally`.
2. **The per-row fallback** folds the condition in that order (`inCodegenOrder`). Under the legacy setting every step but a null test is folded as `coalesce(step, false)`, so the fold stops at the first NULL conjunct as legacy codegen does. `VarkaFilterExecBase.fallbackCondition` passes the child's output and the session's legacy setting when Spark would compile the filter.
3. **The planner** (`behindRaising`) holds each fused conjunct to three orders: written (codegen off, either setting), codegen, and legacy codegen. On top of the existing rules, a fused conjunct that can be NULL on a row reaching a raising residual conjunct, in the written or the codegen order, is demoted: fused, the kernel would drop that row before the residual filter raises on it. The rule reads no conf, so EXPLAIN and the tasks classify a condition the same way in every session. The residual filter's own codegen order is now taken over the Varka node's output, whose fused null tests make their columns non-nullable, since that is what the residual `FilterExec`'s flag reads.
4. **The nightly's Spark fuzzer** draws nested expression trees again (`-Dvarka.sparkfuzz.nested=false` removed): this disagreement was the reason they were off.

The kernel and the emitter are unchanged: a fused node that can raise already declines the batch to the fallback on any lane that would raise, so the fallback decides those rows.

### Why are the changes needed?

Without it Varka gives wrong answers against Spark's default session. Two examples over a row on which `NOT (year(d) = 2021 AND i > 0)` is NULL:

- `... AND x IS NOT NULL AND ym >= INTERVAL '1' YEAR - ym`, all fused, `x` NULL and the subtraction overflowing on the row: Spark drops the row at the `x IS NOT NULL` it now generates before the subtraction; Varka's fallback, following the old lazy placement, evaluated the subtraction first and raised.
- `d > DATE'2000-01-01' AND NOT (year(d) = 2021 AND i > 0) AND (l * 3) > 0` under ANSI, the product residual: Spark goes on past the NULL conjunct and raises on the overflow; Varka fused the NULL conjunct, its kernel dropped the row, and the query answered.

The legacy setting is Spark's own conf, so a session that sets it must get legacy codegen's answer from Varka too.

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

Yes, for Varka: a filter now raises or answers as Spark's filter does after SPARK-60315, under both settings of `spark.sql.legacy.filterShortCircuitOnNullConjunct`, with codegen on and off. Fewer conjuncts fuse where one that can be NULL stands ahead of a residual conjunct that can raise (EXPLAIN gives the reason "it can be NULL on a row on which Spark goes on to evaluate ..."); the `IS NOT NULL` checks the optimizer infers keep the usual comparisons fused. No emitted byte changes.

### How was this patch tested?

- `VarkaConjunctOrderSuite` (catalyst, JUnit): the merged placement on the conditions of upstream's SPARK-60315 tests in `WholeStageCodegenSuite`, transcribed onto the suite's columns, each in the default and the legacy order (a check written before the raising conjunct, the inferred check before the conjunct reading its column, a raising check written first, the flag off when nothing after the NULL conjunct may raise, the nested check after a NULL conjunct); the NULL-ahead demotion with its reason; one case each of the three orders demotes alone; the legacy fold. Two existing cases now expect the demotion of a nullable fused conjunct ahead of a raising one and keep it fused behind the inferred null tests. 21 of 21 pass.
- `VarkaDifferentialSuite` (sql/core): a new test runs six queries through both engines in the four sessions of codegen on/off crossed with the legacy setting on/off - every conjunct fused (the fallback decides), a FALSE conjunct or a null test stopping first, the null test written between the NULL conjunct and the raising one, the NULL conjunct ahead of a raising residual conjunct, a null test written after the raising one (Spark's answer depends on codegen), a date conjunct under ANSI, and an aggregate `FILTER` that Varka does not run.
- Run locally: `VarkaConjunctOrderSuite`, `VarkaExpressionCompilerSuite`, `VarkaCoverageSuite`, `VarkaEmittedBytesSuite` (catalyst, `coverage.json` and `emitted_bytes.json` unchanged); `VarkaDifferentialSuite`, `VarkaFilterExecSuite`, `VarkaFilterRaiseOrderSuite`, `VarkaSplitConditionFusionSuite`, `VarkaRangeFilterFusionSuite`, `VarkaSparkReproducerSuite`, `VarkaCodegenGiveUpSuite` (sql/core). Three existing tests built a nullable fused conjunct ahead of a residual one that Varka counts as able to raise (`add_months` in `VarkaExpressionCompilerSuite`'s size-budget test, `pow` in two `VarkaFilterExecSuite` rule tests), which the new rule demotes; their subjects are the size demotion and the split, so they now run over non-nullable columns.
- Not run here: the PR Build and the option matrix (CI), and the nightly with nested trees, which is the row's last check after the merge.

Review: `/code-review high` on the branch before opening found one issue. `VarkaColumnarRule` asks at planning whether the fallback would hoist a common `AND`'s subexpressions (SPARK-61197, row 541), over the fallback's condition, whose fold the legacy setting changes; the fallback reads the setting when the plan runs. A plan run again after the setting changed could pass the check under one fold and run the other. Fixed by asking the check under both settings, which leaves such a filter to Spark if either fold would hoist; the fallback keeps reading the setting at run time, as `FilterExec` does, rather than binding it into the node. The review read the `codegenOrder` port against the merged `generatePredicateCode` step by step and found no difference.

CI fix: the option matrix (run 44663505883, bin b047) failed the new `VarkaDifferentialSuite` test under `checkIntOverflow=false`: with the overflow check off the kernel wraps the overflowing year-month subtraction instead of declining, so Varka answered `[12]` where Spark raises `INTERVAL_ARITHMETIC_OVERFLOW`. That configuration turns the check off by design, and the residual-conjunct test beside it is already listed for the same reason, so the test now has a `fails` line in `sql/varka/matrix/skips.tsv`; no code changed. Run locally: `dev/varka_matrix.sh --module sql --config checkIntOverflow=false --suites VarkaDifferentialSuite` (the test is cancelled as expected to fail under the configuration and passes under the defaults). `/code-review high` on the branch found no bugs, only five nits in the earlier code, none on this fix; they are left for the author (one says the legacy-fold arm of the hoist check above can never fire).

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

Generated-by: Claude Code (Claude Opus 5.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants