Skip to content

[SPARK-61886][SQL] Fix query failures by CombineFilters when a condition over a column that can fail follows a non-deterministic or throwable one - #60631

Closed
dongjoon-hyun wants to merge 3 commits into
apache:masterfrom
dongjoon-hyun:SPARK-61886
Closed

dongjoon-hyun wants to merge 3 commits into
apache:masterfrom
dongjoon-hyun:SPARK-61886

Conversation

@dongjoon-hyun

@dongjoon-hyun dongjoon-hyun commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

What changes were proposed in this pull request?

This PR fixes CombineFilters so that it does not move a condition over a column that can fail ahead of a non-deterministic or throwable condition written before it. An example is q > 0, where q is an alias of 10L / (id - 3) in ANSI mode.

Since #60157 (SPARK-60980), CombineFilters combines a conjunct of the outer filter written after a non-deterministic or throwable one with the filter below only when ExprUtils.canEvaluateUnconditionally accepts it. That check looks at the conjunct alone. q > 0 compares a column with a literal, so it passes. However, when q is a column of a Project below that is computed with an expression that can fail, the conjunct can fail as that expression does:

  • PushPredicateThroughNonJoin pushes the combined filter below the Project with q replaced by 10L / (id - 3).
  • When the filter is not pushed, e.g. because the Project has a non-deterministic column, whole-stage codegen still computes q for a row only when a filter above first reads it. So the combined filter computes q ahead of the non-deterministic conjunct.

This PR also requires such a conjunct not to read a column that can fail. The columns come from PredicateHelper.failableOutput, which #60574 (SPARK-61823) added for InferFiltersFromConstraints, applied to the child of the filter below:

  • A deterministic column of a Project whose expression ExprUtils.canEvaluateUnconditionally rejects, or that reads such a column of the Project's child.
  • Filter and Sample pass the columns of their child through. Other operators are not looked through.
  • A non-deterministic column is not counted. ProjectExec computes it on every row, and no filter is pushed through a Project with one.

The columns are collected only for a conjunct written after a non-deterministic or throwable one that ExprUtils.canEvaluateUnconditionally accepts.

Outer conjunct written after a non-deterministic or throwable one Before After
Can fail, e.g. 10L / (id - 3) > 0 Kept above Kept above
Can not fail, over columns that can not fail, e.g. id = 1 Combined Combined
Can not fail, over a column that can fail, e.g. q > 0 Combined Kept above

Why are the changes needed?

A query that should succeed fails. With ANSI mode, the default since Apache Spark 4.0.0, a division or a cast is enough.

-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id, q FROM (
  SELECT * FROM (SELECT id, 10L / (id - 3) AS q FROM range(0, 10, 1, 1)) WHERE id >= 0)
WHERE rand(10) * 10 > 100 AND q > 0;

rand(10) * 10 > 100 is false on every row, so q should never be computed for id = 3. With the inner WHERE id >= 0, CombineFilters moves q > 0 into the inner filter, ahead of rand(10) * 10 > 100. The combined filter is then pushed below the projection as 10L / (id - 3) > 0.

Does this PR introduce any user-facing change?

Yes. The query above succeeds. This is a long-standing issue since v3.2.0 (2021-10-06). It is easier to hit since v4.0.0 (2025-05-19), which enables ANSI mode by default. SPARK-60980, which is not released yet, fixed the same failure for a conjunct that can fail by itself, but not for one over a column that can fail.

A conjunct over a column that can fail is no longer combined with the filter below when a non-deterministic or throwable conjunct is written before it. For example, with p an alias of CAST(s AS INT) in ANSI mode, rand() < 0.5 AND p = 1 over another filter keeps p = 1 above with rand() < 0.5. So it does not prune partitions by s anymore, as released versions such as v4.3.0 (2026-10-27) do. For example, with a view whose column d is CAST(dt AS DATE) over a STRING partition column dt and which has a WHERE of its own, rand() < 0.01 AND d = DATE'2026-01-01' over the view no longer prunes partitions by dt. The check is conservative, so the same holds for a column computed with an expression that can not fail but that ExprUtils.canEvaluateUnconditionally does not accept, such as upper(p), as it already does since SPARK-60980 for upper(p) = '1' written directly. A query with a single filter is not affected.

How was this patch tested?

Pass the CIs with the newly added test cases. Both fail without this PR.

  • FilterPushdownSuite: a conjunct over a column that can fail stays above rand(0) > 0.1, also when it reads a column that can not fail as well. The column is an ANSI cast in a Project, which also reaches the conjunct through a Sample, another Project and a Filter. A conjunct over a non-deterministic column or over a widening cast is still combined.
  • DataFrameSuite: the query above, written with the DataFrame API, returns no row in ANSI mode instead of failing with DIVIDE_BY_ZERO.

I also ran the catalyst optimizer suites, DataFrameSuite and the PlanStabilitySuites locally. No golden files change. With a temporary suite (not included), I ran the query above in SQL and with the DataFrame API, before and after this PR, with whole-stage codegen on and off. I also ran a similar query over a Project with a non-deterministic column and an ANSI cast, rand(10) * 10 > 100 AND i > 0 with i the cast. Without this PR, CombineFilters moves i > 0 ahead of the non-deterministic conjunct, and the query fails with CAST_INVALID_INPUT under whole-stage codegen. With this PR, it returns no row.

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

Generated-by: Claude Opus 5.5

…ition over a column that can fail follows a non-deterministic or throwable one
@dongjoon-hyun

Copy link
Copy Markdown
Member Author

Could you review this PR, @viirya ?

@viirya viirya left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The fix looks right to me. With the fix the new FilterPushdownSuite case passes, and with it reverted it fails.

One sibling path is outside this diff. PushPredicateThroughJoin.split partitions the conjuncts by deterministic && !throwable instead of taking a span. So a single filter over a join still moves a later conjunct ahead of rand(), with no CombineFilters involved. Both of these fail with DIVIDE_BY_ZERO on master in ANSI mode:

SELECT * FROM (SELECT id, 10L / (id - 3) AS q FROM range(0, 10, 1, 1)) a
JOIN range(0, 10, 1, 1) r ON a.id = r.id
WHERE rand(10) * 10 > 100 AND q > 0;

SELECT * FROM range(0, 10, 1, 1) t JOIN range(0, 10, 1, 1) r ON t.id = r.id
WHERE rand(10) * 10 > 100 AND 10L / (t.id - 3) > 0;

The second query is the SPARK-60980 case itself, reached through a join. This doesn't need to block this PR. Is there an umbrella JIRA that tracks these rules, so the remaining ones get covered?

val (leading, following) =
splitConjunctivePredicates(fc).span(p => p.deterministic && !p.throwable)
val (cannotFail, rest) = following.partition(ExprUtils.canEvaluateUnconditionally)
lazy val failable = failableOutput(grandChild)

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.

Since this reuses failableOutput, it also inherits the operators the helper doesn't look through, which were raised on #60574. For example, with Filter(rand() > 0.1 AND q > 0, Filter(c, Limit(Project(10L / (id - 3) AS q, ...)))), q > 0 is still combined into the lower filter. Under whole-stage codegen, that filter then computes q first.

Separately, a conjunct kept above now shares a non-deterministic Filter with rand(). ScanOperation doesn't push that filter down, so a view column like CAST(dt AS DATE) AS d no longer gets partition pruning from rand() < 0.01 AND d = .... This is consistent with the single-filter case, but SPARK-61823 added a legacy flag for a similar trade-off. Should this have one too, or a line in the migration guide?

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, extending the helper for both callers separately makes sense.

On pruning, though, the dropped pruning did ship. v4.3.0's CombineFilters still uses partition, so every release since SPARK-35273 combines d = ... from rand() < 0.01 AND d = ... and prunes by it. SPARK-60980's description notes it keeps exactly that. It's this PR that drops it when d is a failable alias, like a view's CAST(dt AS DATE) AS d. I'm fine without a flag. Could the user-facing section say that such a query no longer prunes partitions by dt, as SPARK-60980's description did for upper(p) = '1'?

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.

You are right, thank you for the correction. v4.3.0's CombineFilters combines d = ... and prunes by it, so this PR is what drops it. I updated the user-facing section to say that such a query no longer prunes partitions by dt, as SPARK-60980 did for upper(p) = '1'.

val originalQuery = projected
.where($"a" > 0)
.where($"a" > 1)
.where(Rand(0) > 0.1 && $"i" > 0 && $"j" && $"r" > 0.5)

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.

Every deterministic column read after Rand(0) here is failable. So if failableOutput treated every deterministic alias as failable, this test would still pass. Could you add a conjunct after Rand(0) over a column that can't fail? For example, the pass-through $"a", or an alias such as Cast($"a", LongType).as("w") carried through the same chain. The expected plan would show it combined.

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.

Good point. I added w (Cast(a, LongType)) carried through the same chain and a w > 0 conjunct after Rand(0); the expected plan combines it (2ce79ea). The test now fails if every deterministic alias is treated as failable.

@dongjoon-hyun

Copy link
Copy Markdown
Member Author

Thank you for the review, @viirya. Good catch on the join path, and agreed it is outside this PR. PushPredicateThroughJoin.split partitions by deterministic && !throwable instead of taking a span, so both queries fail without CombineFilters. There is no umbrella JIRA yet; I will file a separate one and handle the join path there.

@viirya viirya left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update. The new w case covers the accept side; with every deterministic alias treated as failable, the test now fails. LGTM, pending CI. One note on the PR description is inline.

@dongjoon-hyun

Copy link
Copy Markdown
Member Author

Thank you so much, @viirya !

@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

CombineFilters now keeps a conjunct written after a non-deterministic or throwable one in the upper filter when it reads a column that failableOutput reports as able to fail, the same check InferFiltersFromConstraints already applies, so the ANSI-mode query in the description returns no row instead of failing with DIVIDE_BY_ZERO, as the new DataFrameSuite test asserts. By this review's reading, SQL queries reach the check the same way as the DataFrame API, including through views, subqueries and hints, which are removed before the rule runs. Columns computed below operators other than Project, Filter and Sample, such as Limit, and filters over joins stay out of scope, as the author plans separate changes for them.

The new tests leave one gap: every conjunct they place reads a single column, so they would not catch the check being changed from any column to every column. The inline comment on FilterPushdownSuite.scala suggests one more conjunct.

Two questions for the author follow under Decision challenges.

Cross-cutting observations

  • Both decision challenges listed below concern one effect of this change: a conjunct it keeps next to the non-deterministic one, in a filter that sits on another filter, no longer reaches partition pruning or data source filter pushdown, and the PR description does not mention that effect yet.

    The two can be settled independently, since a rollback flag or migration note leaves unchanged which columns count as able to fail, and a finer classification still leaves the pruning lost for columns that really can fail.

    Related:

    • Conjuncts over columns such as upper(region), which cannot fail, lose partition pruning
    • No legacy flag or migration note for the partition pruning v4.3.0 users lose

Findings

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

Nit (P3)

  • New tests would not catch the column check changing from any column to every column — sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:202-206 — see inline.

PR description suggestions

  • In "Does this PR introduce any user-facing change?", add that a conjunct kept above no longer reaches partition pruning or data source filter pushdown when another filter is below it. For example, with a view column d defined as CAST(dt AS DATE) over a STRING partition column dt and a WHERE of its own, rand() < 0.01 AND d = DATE'2026-01-01' over the view no longer prunes partitions by dt, as released versions such as v4.3.0 do. Because the check is conservative, the same holds for a column whose expression cannot fail but is not on its list, such as upper(p). A query with a single filter still prunes. This follows up on an existing discussion.

Decision challenges

Conjuncts over columns such as upper(region), which cannot fail, lose partition pruning

Location: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:2638

With this PR, a condition on a column computed with an expression that cannot fail but is not declared total, such as upper(region), no longer gets partition pruning or data source filter pushdown when it follows a non-deterministic conjunct in a filter over another filter, so such a query reads every partition the lower filter admits.

Take T partitioned by dt and region, and spark.table("T").withColumn("ru", upper($"region")).where($"dt" >= "2024-01-01").where(rand() < 0.01 && $"ru" === "US"). On the base branch, as in v4.3.0, CombineFilters moves ru = 'US' into the lower filter, which is pushed below the projection as upper(region) = 'US', and partitions are pruned by both dt and region. Because upper cannot raise, that plan is already correct, so the fix removes no failure for this query. With this PR, failableOutput counts ru as a column that can fail, because Upper does not declare isTotal, so the conjunct stays next to rand() and, by this review's reading of the scan planning rules, only dt prunes. The same applies to lower, trim, IF and CASE WHEN, among other expressions that ExprUtils.canEvaluateUnconditionally does not accept, and the PR description does not mention it. Unlike the pruning given up for an ANSI cast, this loss is not needed for the fix. Removing it takes a broader change: declaring such expressions total, which also changes what InferFiltersFromConstraints and ConstantPropagation do with them and needs every eval and codegen path checked, the kind of change SPARK-60882 made in a PR of its own.

The review leans toward deferring that change with a TODO, because a cost beyond what the fix needs is acceptable once the code marks the broader change that would remove it as deferred, and keeping this PR small is reason enough to defer it. Options:

  • Keep the check as it is: the query above prunes only by dt, as a directly written upper(region) = 'US' after rand() already does on the base branch; nothing changes.
  • Defer it: add a TODO beside the failableOutput condition in CombineFilters (Optimizer.scala lines 2638-2641) saying that a column whose expression cannot fail but does not declare isTotal, such as upper(p), still counts as able to fail and so loses pruning, and mention it in the PR description; the query above still prunes only by dt.
  • Extend it now: make Upper, Lower, StringTrim and similar expressions total (mix in NoThrow or override isTotal) after checking every eval mode, input type and collation, update the list in ExprUtilsSuite, and add a FilterPushdownSuite case; the query above then prunes by region again, and so does a directly written upper(region) = 'US'.

No legacy flag or migration note for the partition pruning v4.3.0 users lose

Location: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:2640

Adding to the inline discussion on partition pruning: this review read CombineFilters in the v4.3.0 tag itself (lines 2342-2344 of Optimizer.scala there). It moves every deterministic, non-throwable conjunct of the outer filter into the lower one, so v4.3.0 combines d = DATE'2026-01-01' from rand() < 0.01 AND d = DATE'2026-01-01' and prunes by it. The loss is also specific to stacked filters: with t partitioned by the STRING column dt and a view v defined as SELECT * FROM (SELECT CAST(dt AS DATE) AS d, x FROM t) WHERE x > 0, SELECT * FROM v WHERE rand() < 0.01 AND d = DATE'2026-01-01' reads every partition with this PR, while the same predicate over a view without its own WHERE still prunes by dt, because that single filter is the one directly on the scan. Keeping the conjunct out of pruning is part of what the fix needs, since pruning by it would evaluate CAST(dt AS DATE) on every partition value before rand(). What remains open is how the change ships to users upgrading from v4.3.0, since the reason given for shipping without a flag or a migration note, that no release has this behavior, does not hold.

The review leans toward an internal legacy flag plus a migration-guide entry, because a change that takes away behavior users of a released version rely on should ship with a way to restore it and a note that explains it, as SPARK-61823 did for inferred filters with spark.sql.legacy.inferFailableFiltersFromConstraints. Options:

  • Ship as is and only update the PR description, as viirya asked: after upgrading from v4.3.0, the query above reads every partition and no setting restores the pruning.
  • Add a migration-guide entry under the release that first ships this, saying that a conjunct over a column that can fail, written after a non-deterministic or throwable one, is no longer combined with the filter below, so such a query can read more data, for example no longer pruning by dt for the view column CAST(dt AS DATE); the optimizer is unchanged.
  • Also add an internal legacy flag, false by default, that makes CombineFilters skip the failableOutput condition when true, and name it in that entry: with the flag set, the query above would prune by dt again, as in v4.3.0, and could again fail on a dt partition value that is not a valid date.

This follows up on an existing discussion.

Generated by Omnigent on Databricks

Comment on lines +202 to +206
.where(Rand(0) > 0.1 && $"i" > 0 && $"j" && $"w" > 0 && $"r" > 0.5)

val correctAnswer = projected
.where($"a" > 0 && $"a" > 1 && $"w" > 0 && $"r" > 0.5)
.where(Rand(0) > 0.1 && $"i" > 0 && $"j")

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.

Nit (P3): Each conjunct this test places after Rand(0) reads a single column, and so does q > 0 in the new DataFrameSuite case, so neither test would notice if the check in CombineFilters changed from "any column it reads can fail" (!p.references.exists(failable.contains)) to "every column it reads can fail", for example !p.references.subsetOf(failable). With that change, by this review's reading, a conjunct such as q > id in the DataFrameSuite shape would be combined again, pushed below the projection as 10L / (id - 3) > id, and fail with DIVIDE_BY_ZERO on id 3. A conjunct that reads both a column that can fail and one that cannot, expected in the upper filter, pins the rule:

Suggested change
.where(Rand(0) > 0.1 && $"i" > 0 && $"j" && $"w" > 0 && $"r" > 0.5)
val correctAnswer = projected
.where($"a" > 0 && $"a" > 1 && $"w" > 0 && $"r" > 0.5)
.where(Rand(0) > 0.1 && $"i" > 0 && $"j")
.where(Rand(0) > 0.1 && $"i" > 0 && $"j" && $"i" > $"a" && $"w" > 0 && $"r" > 0.5)
val correctAnswer = projected
.where($"a" > 0 && $"a" > 1 && $"w" > 0 && $"r" > 0.5)
.where(Rand(0) > 0.1 && $"i" > 0 && $"j" && $"i" > $"a")

Verification:

  • Regression: Changing the check so that it keeps a conjunct above only when every column the conjunct reads can fail makes the plan test fail, because the mixed conjunct is then combined into the filter below.
  • Behavior: With the current check, the plan test expects the mixed conjunct in the upper filter together with the other conjuncts over columns that can fail, and still expects the conjuncts over the widening-cast alias and the non-deterministic column combined into the filter below.

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.

Thanks. I added i > a, which reads both a column that can fail and one that can not, and the expected plan keeps it above (dbf2207). The test now fails if the check becomes subsetOf.

@dongjoon-hyun

Copy link
Copy Markdown
Member Author

Thank you for the review, @spark-test.

  • upper(region): I will keep the check as is. Since SPARK-60980, upper(region) = 'US' written directly after rand() already stays above, so the alias now behaves the same. Declaring such expressions total is a separate change, like SPARK-60882. The PR description now mentions it.
  • Legacy flag and migration guide: as discussed with viirya, I will ship without a flag and only describe the pruning change in the PR description, as SPARK-60980 did for the same trade-off.

@dongjoon-hyun

Copy link
Copy Markdown
Member Author

Thank you, @HyukjinKwon .

@github-actions github-actions Bot added the SQL label Nov 18, 2026
@dongjoon-hyun

Copy link
Copy Markdown
Member Author

There was only one known failure which was fixed in master branch already.

dongjoon-hyun added a commit that referenced this pull request Nov 18, 2026
…ition over a column that can fail follows a non-deterministic or throwable one

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

This PR fixes `CombineFilters` so that it does not move a condition over a column that can fail ahead of a non-deterministic or throwable condition written before it. An example is `q > 0`, where `q` is an alias of `10L / (id - 3)` in ANSI mode.

Since #60157 (SPARK-60980), `CombineFilters` combines a conjunct of the outer filter written after a non-deterministic or throwable one with the filter below only when `ExprUtils.canEvaluateUnconditionally` accepts it. That check looks at the conjunct alone. `q > 0` compares a column with a literal, so it passes. However, when `q` is a column of a `Project` below that is computed with an expression that can fail, the conjunct can fail as that expression does:

- `PushPredicateThroughNonJoin` pushes the combined filter below the `Project` with `q` replaced by `10L / (id - 3)`.
- When the filter is not pushed, e.g. because the `Project` has a non-deterministic column, whole-stage codegen still computes `q` for a row only when a filter above first reads it. So the combined filter computes `q` ahead of the non-deterministic conjunct.

This PR also requires such a conjunct not to read a column that can fail. The columns come from `PredicateHelper.failableOutput`, which #60574 (SPARK-61823) added for `InferFiltersFromConstraints`, applied to the child of the filter below:

- A deterministic column of a `Project` whose expression `ExprUtils.canEvaluateUnconditionally` rejects, or that reads such a column of the `Project`'s child.
- `Filter` and `Sample` pass the columns of their child through. Other operators are not looked through.
- A non-deterministic column is not counted. `ProjectExec` computes it on every row, and no filter is pushed through a `Project` with one.

The columns are collected only for a conjunct written after a non-deterministic or throwable one that `ExprUtils.canEvaluateUnconditionally` accepts.

| Outer conjunct written after a non-deterministic or throwable one | Before | After |
|---|---|---|
| Can fail, e.g. `10L / (id - 3) > 0` | Kept above | Kept above |
| Can not fail, over columns that can not fail, e.g. `id = 1` | Combined | Combined |
| Can not fail, over a column that can fail, e.g. `q > 0` | Combined | Kept above |

### Why are the changes needed?

A query that should succeed fails. With ANSI mode, the default since Apache Spark 4.0.0, a division or a cast is enough.

```sql
-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id, q FROM (
  SELECT * FROM (SELECT id, 10L / (id - 3) AS q FROM range(0, 10, 1, 1)) WHERE id >= 0)
WHERE rand(10) * 10 > 100 AND q > 0;
```

`rand(10) * 10 > 100` is false on every row, so `q` should never be computed for `id = 3`. With the inner `WHERE id >= 0`, `CombineFilters` moves `q > 0` into the inner filter, ahead of `rand(10) * 10 > 100`. The combined filter is then pushed below the projection as `10L / (id - 3) > 0`.

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

Yes. The query above succeeds. This is a long-standing issue since [v3.2.0](https://github.com/apache/spark/releases/tag/v3.2.0) (2021-10-06). It is easier to hit since [v4.0.0](https://github.com/apache/spark/releases/tag/v4.0.0) (2025-05-19), which enables ANSI mode by default. SPARK-60980, which is not released yet, fixed the same failure for a conjunct that can fail by itself, but not for one over a column that can fail.

A conjunct over a column that can fail is no longer combined with the filter below when a non-deterministic or throwable conjunct is written before it. For example, with `p` an alias of `CAST(s AS INT)` in ANSI mode, `rand() < 0.5 AND p = 1` over another filter keeps `p = 1` above with `rand() < 0.5`. So it does not prune partitions by `s` anymore, as released versions such as [v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) (2026-10-27) do. For example, with a view whose column `d` is `CAST(dt AS DATE)` over a STRING partition column `dt` and which has a `WHERE` of its own, `rand() < 0.01 AND d = DATE'2026-01-01'` over the view no longer prunes partitions by `dt`. The check is conservative, so the same holds for a column computed with an expression that can not fail but that `ExprUtils.canEvaluateUnconditionally` does not accept, such as `upper(p)`, as it already does since SPARK-60980 for `upper(p) = '1'` written directly. A query with a single filter is not affected.

### How was this patch tested?

Pass the CIs with the newly added test cases. Both fail without this PR.

- `FilterPushdownSuite`: a conjunct over a column that can fail stays above `rand(0) > 0.1`, also when it reads a column that can not fail as well. The column is an ANSI cast in a `Project`, which also reaches the conjunct through a `Sample`, another `Project` and a `Filter`. A conjunct over a non-deterministic column or over a widening cast is still combined.
- `DataFrameSuite`: the query above, written with the DataFrame API, returns no row in ANSI mode instead of failing with `DIVIDE_BY_ZERO`.

I also ran the catalyst optimizer suites, `DataFrameSuite` and the `PlanStabilitySuite`s locally. No golden files change. With a temporary suite (not included), I ran the query above in SQL and with the DataFrame API, before and after this PR, with whole-stage codegen on and off. I also ran a similar query over a `Project` with a non-deterministic column and an ANSI cast, `rand(10) * 10 > 100 AND i > 0` with `i` the cast. Without this PR, `CombineFilters` moves `i > 0` ahead of the non-deterministic conjunct, and the query fails with `CAST_INVALID_INPUT` under whole-stage codegen. With this PR, it returns no row.

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

Generated-by: Claude Opus 5.5

Closes #60631 from dongjoon-hyun/SPARK-61886.

Authored-by: Dongjoon Hyun <dongjoon@apache.org>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>

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


skip-checks: true
dongjoon-hyun added a commit that referenced this pull request Nov 18, 2026
…ition over a column that can fail follows a non-deterministic or throwable one

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

This PR fixes `CombineFilters` so that it does not move a condition over a column that can fail ahead of a non-deterministic or throwable condition written before it. An example is `q > 0`, where `q` is an alias of `10L / (id - 3)` in ANSI mode.

Since #60157 (SPARK-60980), `CombineFilters` combines a conjunct of the outer filter written after a non-deterministic or throwable one with the filter below only when `ExprUtils.canEvaluateUnconditionally` accepts it. That check looks at the conjunct alone. `q > 0` compares a column with a literal, so it passes. However, when `q` is a column of a `Project` below that is computed with an expression that can fail, the conjunct can fail as that expression does:

- `PushPredicateThroughNonJoin` pushes the combined filter below the `Project` with `q` replaced by `10L / (id - 3)`.
- When the filter is not pushed, e.g. because the `Project` has a non-deterministic column, whole-stage codegen still computes `q` for a row only when a filter above first reads it. So the combined filter computes `q` ahead of the non-deterministic conjunct.

This PR also requires such a conjunct not to read a column that can fail. The columns come from `PredicateHelper.failableOutput`, which #60574 (SPARK-61823) added for `InferFiltersFromConstraints`, applied to the child of the filter below:

- A deterministic column of a `Project` whose expression `ExprUtils.canEvaluateUnconditionally` rejects, or that reads such a column of the `Project`'s child.
- `Filter` and `Sample` pass the columns of their child through. Other operators are not looked through.
- A non-deterministic column is not counted. `ProjectExec` computes it on every row, and no filter is pushed through a `Project` with one.

The columns are collected only for a conjunct written after a non-deterministic or throwable one that `ExprUtils.canEvaluateUnconditionally` accepts.

| Outer conjunct written after a non-deterministic or throwable one | Before | After |
|---|---|---|
| Can fail, e.g. `10L / (id - 3) > 0` | Kept above | Kept above |
| Can not fail, over columns that can not fail, e.g. `id = 1` | Combined | Combined |
| Can not fail, over a column that can fail, e.g. `q > 0` | Combined | Kept above |

### Why are the changes needed?

A query that should succeed fails. With ANSI mode, the default since Apache Spark 4.0.0, a division or a cast is enough.

```sql
-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id, q FROM (
  SELECT * FROM (SELECT id, 10L / (id - 3) AS q FROM range(0, 10, 1, 1)) WHERE id >= 0)
WHERE rand(10) * 10 > 100 AND q > 0;
```

`rand(10) * 10 > 100` is false on every row, so `q` should never be computed for `id = 3`. With the inner `WHERE id >= 0`, `CombineFilters` moves `q > 0` into the inner filter, ahead of `rand(10) * 10 > 100`. The combined filter is then pushed below the projection as `10L / (id - 3) > 0`.

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

Yes. The query above succeeds. This is a long-standing issue since [v3.2.0](https://github.com/apache/spark/releases/tag/v3.2.0) (2021-10-06). It is easier to hit since [v4.0.0](https://github.com/apache/spark/releases/tag/v4.0.0) (2025-05-19), which enables ANSI mode by default. SPARK-60980, which is not released yet, fixed the same failure for a conjunct that can fail by itself, but not for one over a column that can fail.

A conjunct over a column that can fail is no longer combined with the filter below when a non-deterministic or throwable conjunct is written before it. For example, with `p` an alias of `CAST(s AS INT)` in ANSI mode, `rand() < 0.5 AND p = 1` over another filter keeps `p = 1` above with `rand() < 0.5`. So it does not prune partitions by `s` anymore, as released versions such as [v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) (2026-10-27) do. For example, with a view whose column `d` is `CAST(dt AS DATE)` over a STRING partition column `dt` and which has a `WHERE` of its own, `rand() < 0.01 AND d = DATE'2026-01-01'` over the view no longer prunes partitions by `dt`. The check is conservative, so the same holds for a column computed with an expression that can not fail but that `ExprUtils.canEvaluateUnconditionally` does not accept, such as `upper(p)`, as it already does since SPARK-60980 for `upper(p) = '1'` written directly. A query with a single filter is not affected.

### How was this patch tested?

Pass the CIs with the newly added test cases. Both fail without this PR.

- `FilterPushdownSuite`: a conjunct over a column that can fail stays above `rand(0) > 0.1`, also when it reads a column that can not fail as well. The column is an ANSI cast in a `Project`, which also reaches the conjunct through a `Sample`, another `Project` and a `Filter`. A conjunct over a non-deterministic column or over a widening cast is still combined.
- `DataFrameSuite`: the query above, written with the DataFrame API, returns no row in ANSI mode instead of failing with `DIVIDE_BY_ZERO`.

I also ran the catalyst optimizer suites, `DataFrameSuite` and the `PlanStabilitySuite`s locally. No golden files change. With a temporary suite (not included), I ran the query above in SQL and with the DataFrame API, before and after this PR, with whole-stage codegen on and off. I also ran a similar query over a `Project` with a non-deterministic column and an ANSI cast, `rand(10) * 10 > 100 AND i > 0` with `i` the cast. Without this PR, `CombineFilters` moves `i > 0` ahead of the non-deterministic conjunct, and the query fails with `CAST_INVALID_INPUT` under whole-stage codegen. With this PR, it returns no row.

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

Generated-by: Claude Opus 5.5

Closes #60631 from dongjoon-hyun/SPARK-61886.

Authored-by: Dongjoon Hyun <dongjoon@apache.org>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>

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

Copy link
Copy Markdown
Member Author

Merge Summary:

Posted by merge_spark_pr.py

dongjoon-hyun added a commit that referenced this pull request Nov 18, 2026
…hen a condition that can fail follows a non-deterministic or throwable one

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

This PR fixes `PushPredicateThroughJoin` so that it does not move a condition that can fail, such as a division in ANSI mode, ahead of a non-deterministic or throwable condition written before it.

For a filter over a join, `PushPredicateThroughJoin` pushes a conjunct over one side into that side. For an inner join, it also moves a conjunct over both sides into the join condition. Either way, the conjunct is evaluated before the filter. Since #20069 (SPARK-22895), `split` moves every deterministic conjunct with `partition`, no matter where it is written, and #44716 (SPARK-46707) later kept a throwable one in place too. So a conjunct written after a non-deterministic or throwable one is evaluated ahead of it, on rows that the `AND` short-circuit would have kept from it. This is the failure that #60157 (SPARK-60980) fixed for `CombineFilters`, here reached through a join with a single filter.

This PR splits the conjuncts with `span` instead, as `CombineFilters` does. After the first non-deterministic or throwable conjunct, a conjunct moves only when it can not fail:

- `ExprUtils.canEvaluateUnconditionally` accepts it, e.g. a comparison of columns and literals.
- It reads no column of either side that `PredicateHelper.failableOutput` (#60574, SPARK-61823) reports. An example is `q > 0`, where `q` is an alias of `10L / (id - 3)` in a `Project` below the join. Pushed into that side, the conjunct would then be pushed below the `Project` as `10L / (id - 3) > 0`.

| Conjunct written after a non-deterministic or throwable one | Before | After |
|---|---|---|
| Can fail, e.g. `10L / (t.id - 3) > 0` | Moved | Kept in place |
| Can not fail, over a column that can fail, e.g. `q > 0` | Moved | Kept in place |
| Can not fail, over columns that can not fail, e.g. `t.id > 5` | Moved | Moved |

The conjuncts kept in place stay in their written order. Before, a conjunct kept in the filter above an outer join, e.g. one over the right side of a left outer join, was placed ahead of the non-deterministic conjunct.

Every case of the rule goes through `split`, so this covers:

- A filter over a join of any type that the rule handles, and over an as-of join.
- A filter over an inner join: a conjunct kept in place is not moved into the join condition either.
- A join condition: a conjunct written after a throwable one stays in the condition. A join condition can not have a non-deterministic conjunct.
- An external lookup join: `splitLookupJoin` decides it over all the conjuncts. A non-deterministic conjunct such as `rand() < 0.5` has no references, and it is set aside before `split` sees the others.

### Why are the changes needed?

A query that should succeed fails. With ANSI mode, the default since Apache Spark 4.0.0, a division or a cast is enough.

```sql
-- Issue 1: It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT * FROM range(0, 10, 1, 1) t JOIN range(0, 10, 1, 1) r ON t.id = r.id
WHERE rand(10) * 10 > 100 AND 10L / (t.id - 3) > 0;

-- Issue 2: It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT * FROM range(0, 10, 1, 1) t LEFT JOIN range(0, 10, 1, 1) r ON t.id = r.id
WHERE rand(10) * 10 > 100 AND coalesce(10L / (r.id - 3), 1L) > 0;
```

`rand(10) * 10 > 100` is false on every row, so the division should never run for `t.id = 3` or `r.id = 3`. In Issue 1, `PushPredicateThroughJoin` pushes `10L / (t.id - 3) > 0` into the left side, below the join. In Issue 2, it keeps the conjunct over the right side above the left outer join, but puts it ahead of `rand(10) * 10 > 100`. A throwable conjunct written first, such as a `CASE WHEN` with `raise_error`, causes the same failure.

The other query reported in the review of #60631, with `q > 0` where `q` is an alias of `10L / (id - 3)` in the left side, still fails with the default configurations. There, `InferFiltersFromConstraints` adds `isnotnull(q)` ahead of `rand(10) * 10 > 100`, since `failableOutput` does not look through a join, and that filter is then pushed. With `spark.sql.constraintPropagation.enabled=false`, or with `q IS NULL` instead of `q > 0`, the query returns no row with this PR under whole-stage codegen. For the same reason, a conjunct over such a column is still pushed when its join is a side of another join. For example, `rand() > 0.1 AND q > 0` over `(tq JOIN r) LEFT JOIN s`, where `tq` computes `q`, pushes `q > 0` into the inner join, where no conjunct is written before it, and then below the projection as `10L / (id - 3) > 0`. This PR does not change `failableOutput`. #60643 (SPARK-61921) makes it look through a join, which covers both cases.

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

Yes. The queries above succeed. This is a long-standing issue since [v2.3.0](https://github.com/apache/spark/releases/tag/v2.3.0) (2018-02-22). I confirmed that both issues fail with `DIVIDE_BY_ZERO` in ANSI mode on the released [v3.5.9](https://github.com/apache/spark/releases/tag/v3.5.9) (2026-07-12), [v4.0.5](https://github.com/apache/spark/releases/tag/v4.0.5) (2026-10-21) and [v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) (2026-10-27). It is easier to hit since [v4.0.0](https://github.com/apache/spark/releases/tag/v4.0.0) (2025-05-19), which enables ANSI mode by default.

A conjunct written after a non-deterministic or throwable one is no longer pushed below a join or moved into its condition, unless it can not fail. For example, `rand() < 0.5 AND CAST(t.s AS INT) = 1` over a join keeps `CAST(t.s AS INT) = 1` above the join with `rand() < 0.5`, so it no longer prunes the partitions of `t`. Likewise, an equality over both sides of an inner join that can fail is no longer moved into the join condition. For example, `SELECT * FROM t, r WHERE rand() < 0.5 AND t.id + 1 = r.id` in ANSI mode is planned as a join without a condition and a filter above it, instead of an equi-join on `t.id + 1 = r.id`. A conjunct written before the non-deterministic or throwable one is not affected, nor is a condition written in the `ON` clause.

### How was this patch tested?

Pass the CIs with the newly added test cases. They fail without this PR.

- `FilterPushdownSuite`: over an inner join, a division written after `rand(0) > 0.1`, and conditions over a column of either side that can fail, stay above the join. An ANSI addition compared over both sides is not moved into the join condition either, so the join has no condition. A condition over a column that can not fail, and a division written before `rand(0) > 0.1`, are pushed.
- `PushPredicateThroughExternalLookupJoinSuite`: an ANSI addition over both sides written after a non-deterministic conjunct does not move into the condition of an inner lookup join. An existing case now writes its conjunct over both sides, an addition that can overflow in ANSI mode, before the throwing one, since it no longer moves when written after it.
- `DataFrameSuite`: Issue 1, written with the DataFrame API, returns no row in ANSI mode instead of failing with `DIVIDE_BY_ZERO`.

I also ran the catalyst optimizer suites, `DataFrameSuite`, the `PlanStabilitySuite`s, the external lookup join suites in `sql/core` and `SQLQueryTestSuite` locally. No golden files change. With a temporary suite (not included), I ran Issues 1 and 2 before and after this PR, along with right outer, left semi and as-of joins, a division over both sides of an inner join, and a throwable `CASE WHEN` with `raise_error` in the `WHERE` or the `ON` clause. I ran each with whole-stage codegen on and off. All of them fail before this PR and succeed after it. The query with `q IS NULL` above also fails before this PR, and returns no row after it under whole-stage codegen.

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

Generated-by: Claude Opus 5.5

Closes #60646 from dongjoon-hyun/SPARK-61924.

Authored-by: Dongjoon Hyun <dongjoon@apache.org>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>


skip-checks: true
dongjoon-hyun added a commit that referenced this pull request Nov 18, 2026
…hen a condition that can fail follows a non-deterministic or throwable one

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

This PR fixes `PushPredicateThroughJoin` so that it does not move a condition that can fail, such as a division in ANSI mode, ahead of a non-deterministic or throwable condition written before it.

For a filter over a join, `PushPredicateThroughJoin` pushes a conjunct over one side into that side. For an inner join, it also moves a conjunct over both sides into the join condition. Either way, the conjunct is evaluated before the filter. Since #20069 (SPARK-22895), `split` moves every deterministic conjunct with `partition`, no matter where it is written, and #44716 (SPARK-46707) later kept a throwable one in place too. So a conjunct written after a non-deterministic or throwable one is evaluated ahead of it, on rows that the `AND` short-circuit would have kept from it. This is the failure that #60157 (SPARK-60980) fixed for `CombineFilters`, here reached through a join with a single filter.

This PR splits the conjuncts with `span` instead, as `CombineFilters` does. After the first non-deterministic or throwable conjunct, a conjunct moves only when it can not fail:

- `ExprUtils.canEvaluateUnconditionally` accepts it, e.g. a comparison of columns and literals.
- It reads no column of either side that `PredicateHelper.failableOutput` (#60574, SPARK-61823) reports. An example is `q > 0`, where `q` is an alias of `10L / (id - 3)` in a `Project` below the join. Pushed into that side, the conjunct would then be pushed below the `Project` as `10L / (id - 3) > 0`.

| Conjunct written after a non-deterministic or throwable one | Before | After |
|---|---|---|
| Can fail, e.g. `10L / (t.id - 3) > 0` | Moved | Kept in place |
| Can not fail, over a column that can fail, e.g. `q > 0` | Moved | Kept in place |
| Can not fail, over columns that can not fail, e.g. `t.id > 5` | Moved | Moved |

The conjuncts kept in place stay in their written order. Before, a conjunct kept in the filter above an outer join, e.g. one over the right side of a left outer join, was placed ahead of the non-deterministic conjunct.

Every case of the rule goes through `split`, so this covers:

- A filter over a join of any type that the rule handles, and over an as-of join.
- A filter over an inner join: a conjunct kept in place is not moved into the join condition either.
- A join condition: a conjunct written after a throwable one stays in the condition. A join condition can not have a non-deterministic conjunct.
- An external lookup join: `splitLookupJoin` decides it over all the conjuncts. A non-deterministic conjunct such as `rand() < 0.5` has no references, and it is set aside before `split` sees the others.

### Why are the changes needed?

A query that should succeed fails. With ANSI mode, the default since Apache Spark 4.0.0, a division or a cast is enough.

```sql
-- Issue 1: It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT * FROM range(0, 10, 1, 1) t JOIN range(0, 10, 1, 1) r ON t.id = r.id
WHERE rand(10) * 10 > 100 AND 10L / (t.id - 3) > 0;

-- Issue 2: It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT * FROM range(0, 10, 1, 1) t LEFT JOIN range(0, 10, 1, 1) r ON t.id = r.id
WHERE rand(10) * 10 > 100 AND coalesce(10L / (r.id - 3), 1L) > 0;
```

`rand(10) * 10 > 100` is false on every row, so the division should never run for `t.id = 3` or `r.id = 3`. In Issue 1, `PushPredicateThroughJoin` pushes `10L / (t.id - 3) > 0` into the left side, below the join. In Issue 2, it keeps the conjunct over the right side above the left outer join, but puts it ahead of `rand(10) * 10 > 100`. A throwable conjunct written first, such as a `CASE WHEN` with `raise_error`, causes the same failure.

The other query reported in the review of #60631, with `q > 0` where `q` is an alias of `10L / (id - 3)` in the left side, still fails with the default configurations. There, `InferFiltersFromConstraints` adds `isnotnull(q)` ahead of `rand(10) * 10 > 100`, since `failableOutput` does not look through a join, and that filter is then pushed. With `spark.sql.constraintPropagation.enabled=false`, or with `q IS NULL` instead of `q > 0`, the query returns no row with this PR under whole-stage codegen. For the same reason, a conjunct over such a column is still pushed when its join is a side of another join. For example, `rand() > 0.1 AND q > 0` over `(tq JOIN r) LEFT JOIN s`, where `tq` computes `q`, pushes `q > 0` into the inner join, where no conjunct is written before it, and then below the projection as `10L / (id - 3) > 0`. This PR does not change `failableOutput`. #60643 (SPARK-61921) makes it look through a join, which covers both cases.

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

Yes. The queries above succeed. This is a long-standing issue since [v2.3.0](https://github.com/apache/spark/releases/tag/v2.3.0) (2018-02-22). I confirmed that both issues fail with `DIVIDE_BY_ZERO` in ANSI mode on the released [v3.5.9](https://github.com/apache/spark/releases/tag/v3.5.9) (2026-07-12), [v4.0.5](https://github.com/apache/spark/releases/tag/v4.0.5) (2026-10-21) and [v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) (2026-10-27). It is easier to hit since [v4.0.0](https://github.com/apache/spark/releases/tag/v4.0.0) (2025-05-19), which enables ANSI mode by default.

A conjunct written after a non-deterministic or throwable one is no longer pushed below a join or moved into its condition, unless it can not fail. For example, `rand() < 0.5 AND CAST(t.s AS INT) = 1` over a join keeps `CAST(t.s AS INT) = 1` above the join with `rand() < 0.5`, so it no longer prunes the partitions of `t`. Likewise, an equality over both sides of an inner join that can fail is no longer moved into the join condition. For example, `SELECT * FROM t, r WHERE rand() < 0.5 AND t.id + 1 = r.id` in ANSI mode is planned as a join without a condition and a filter above it, instead of an equi-join on `t.id + 1 = r.id`. A conjunct written before the non-deterministic or throwable one is not affected, nor is a condition written in the `ON` clause.

### How was this patch tested?

Pass the CIs with the newly added test cases. They fail without this PR.

- `FilterPushdownSuite`: over an inner join, a division written after `rand(0) > 0.1`, and conditions over a column of either side that can fail, stay above the join. An ANSI addition compared over both sides is not moved into the join condition either, so the join has no condition. A condition over a column that can not fail, and a division written before `rand(0) > 0.1`, are pushed.
- `PushPredicateThroughExternalLookupJoinSuite`: an ANSI addition over both sides written after a non-deterministic conjunct does not move into the condition of an inner lookup join. An existing case now writes its conjunct over both sides, an addition that can overflow in ANSI mode, before the throwing one, since it no longer moves when written after it.
- `DataFrameSuite`: Issue 1, written with the DataFrame API, returns no row in ANSI mode instead of failing with `DIVIDE_BY_ZERO`.

I also ran the catalyst optimizer suites, `DataFrameSuite`, the `PlanStabilitySuite`s, the external lookup join suites in `sql/core` and `SQLQueryTestSuite` locally. No golden files change. With a temporary suite (not included), I ran Issues 1 and 2 before and after this PR, along with right outer, left semi and as-of joins, a division over both sides of an inner join, and a throwable `CASE WHEN` with `raise_error` in the `WHERE` or the `ON` clause. I ran each with whole-stage codegen on and off. All of them fail before this PR and succeed after it. The query with `q IS NULL` above also fails before this PR, and returns no row after it under whole-stage codegen.

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

Generated-by: Claude Opus 5.5

Closes #60646 from dongjoon-hyun/SPARK-61924.

Authored-by: Dongjoon Hyun <dongjoon@apache.org>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>

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


skip-checks: true
dongjoon-hyun added a commit that referenced this pull request Nov 18, 2026
…hen a condition that can fail follows a non-deterministic or throwable one

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

This PR fixes `PushPredicateThroughJoin` so that it does not move a condition that can fail, such as a division in ANSI mode, ahead of a non-deterministic or throwable condition written before it.

For a filter over a join, `PushPredicateThroughJoin` pushes a conjunct over one side into that side. For an inner join, it also moves a conjunct over both sides into the join condition. Either way, the conjunct is evaluated before the filter. Since #20069 (SPARK-22895), `split` moves every deterministic conjunct with `partition`, no matter where it is written, and #44716 (SPARK-46707) later kept a throwable one in place too. So a conjunct written after a non-deterministic or throwable one is evaluated ahead of it, on rows that the `AND` short-circuit would have kept from it. This is the failure that #60157 (SPARK-60980) fixed for `CombineFilters`, here reached through a join with a single filter.

This PR splits the conjuncts with `span` instead, as `CombineFilters` does. After the first non-deterministic or throwable conjunct, a conjunct moves only when it can not fail:

- `ExprUtils.canEvaluateUnconditionally` accepts it, e.g. a comparison of columns and literals.
- It reads no column of either side that `PredicateHelper.failableOutput` (#60574, SPARK-61823) reports. An example is `q > 0`, where `q` is an alias of `10L / (id - 3)` in a `Project` below the join. Pushed into that side, the conjunct would then be pushed below the `Project` as `10L / (id - 3) > 0`.

| Conjunct written after a non-deterministic or throwable one | Before | After |
|---|---|---|
| Can fail, e.g. `10L / (t.id - 3) > 0` | Moved | Kept in place |
| Can not fail, over a column that can fail, e.g. `q > 0` | Moved | Kept in place |
| Can not fail, over columns that can not fail, e.g. `t.id > 5` | Moved | Moved |

The conjuncts kept in place stay in their written order. Before, a conjunct kept in the filter above an outer join, e.g. one over the right side of a left outer join, was placed ahead of the non-deterministic conjunct.

Every case of the rule goes through `split`, so this covers:

- A filter over a join of any type that the rule handles, and over an as-of join.
- A filter over an inner join: a conjunct kept in place is not moved into the join condition either.
- A join condition: a conjunct written after a throwable one stays in the condition. A join condition can not have a non-deterministic conjunct.
- An external lookup join: `splitLookupJoin` decides it over all the conjuncts. A non-deterministic conjunct such as `rand() < 0.5` has no references, and it is set aside before `split` sees the others.

### Why are the changes needed?

A query that should succeed fails. With ANSI mode, the default since Apache Spark 4.0.0, a division or a cast is enough.

```sql
-- Issue 1: It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT * FROM range(0, 10, 1, 1) t JOIN range(0, 10, 1, 1) r ON t.id = r.id
WHERE rand(10) * 10 > 100 AND 10L / (t.id - 3) > 0;

-- Issue 2: It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT * FROM range(0, 10, 1, 1) t LEFT JOIN range(0, 10, 1, 1) r ON t.id = r.id
WHERE rand(10) * 10 > 100 AND coalesce(10L / (r.id - 3), 1L) > 0;
```

`rand(10) * 10 > 100` is false on every row, so the division should never run for `t.id = 3` or `r.id = 3`. In Issue 1, `PushPredicateThroughJoin` pushes `10L / (t.id - 3) > 0` into the left side, below the join. In Issue 2, it keeps the conjunct over the right side above the left outer join, but puts it ahead of `rand(10) * 10 > 100`. A throwable conjunct written first, such as a `CASE WHEN` with `raise_error`, causes the same failure.

The other query reported in the review of #60631, with `q > 0` where `q` is an alias of `10L / (id - 3)` in the left side, still fails with the default configurations. There, `InferFiltersFromConstraints` adds `isnotnull(q)` ahead of `rand(10) * 10 > 100`, since `failableOutput` does not look through a join, and that filter is then pushed. With `spark.sql.constraintPropagation.enabled=false`, or with `q IS NULL` instead of `q > 0`, the query returns no row with this PR under whole-stage codegen. For the same reason, a conjunct over such a column is still pushed when its join is a side of another join. For example, `rand() > 0.1 AND q > 0` over `(tq JOIN r) LEFT JOIN s`, where `tq` computes `q`, pushes `q > 0` into the inner join, where no conjunct is written before it, and then below the projection as `10L / (id - 3) > 0`. This PR does not change `failableOutput`. #60643 (SPARK-61921) makes it look through a join, which covers both cases.

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

Yes. The queries above succeed. This is a long-standing issue since [v2.3.0](https://github.com/apache/spark/releases/tag/v2.3.0) (2018-02-22). I confirmed that both issues fail with `DIVIDE_BY_ZERO` in ANSI mode on the released [v3.5.9](https://github.com/apache/spark/releases/tag/v3.5.9) (2026-07-12), [v4.0.5](https://github.com/apache/spark/releases/tag/v4.0.5) (2026-10-21) and [v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) (2026-10-27). It is easier to hit since [v4.0.0](https://github.com/apache/spark/releases/tag/v4.0.0) (2025-05-19), which enables ANSI mode by default.

A conjunct written after a non-deterministic or throwable one is no longer pushed below a join or moved into its condition, unless it can not fail. For example, `rand() < 0.5 AND CAST(t.s AS INT) = 1` over a join keeps `CAST(t.s AS INT) = 1` above the join with `rand() < 0.5`, so it no longer prunes the partitions of `t`. Likewise, an equality over both sides of an inner join that can fail is no longer moved into the join condition. For example, `SELECT * FROM t, r WHERE rand() < 0.5 AND t.id + 1 = r.id` in ANSI mode is planned as a join without a condition and a filter above it, instead of an equi-join on `t.id + 1 = r.id`. A conjunct written before the non-deterministic or throwable one is not affected, nor is a condition written in the `ON` clause.

### How was this patch tested?

Pass the CIs with the newly added test cases. They fail without this PR.

- `FilterPushdownSuite`: over an inner join, a division written after `rand(0) > 0.1`, and conditions over a column of either side that can fail, stay above the join. An ANSI addition compared over both sides is not moved into the join condition either, so the join has no condition. A condition over a column that can not fail, and a division written before `rand(0) > 0.1`, are pushed.
- `PushPredicateThroughExternalLookupJoinSuite`: an ANSI addition over both sides written after a non-deterministic conjunct does not move into the condition of an inner lookup join. An existing case now writes its conjunct over both sides, an addition that can overflow in ANSI mode, before the throwing one, since it no longer moves when written after it.
- `DataFrameSuite`: Issue 1, written with the DataFrame API, returns no row in ANSI mode instead of failing with `DIVIDE_BY_ZERO`.

I also ran the catalyst optimizer suites, `DataFrameSuite`, the `PlanStabilitySuite`s, the external lookup join suites in `sql/core` and `SQLQueryTestSuite` locally. No golden files change. With a temporary suite (not included), I ran Issues 1 and 2 before and after this PR, along with right outer, left semi and as-of joins, a division over both sides of an inner join, and a throwable `CASE WHEN` with `raise_error` in the `WHERE` or the `ON` clause. I ran each with whole-stage codegen on and off. All of them fail before this PR and succeed after it. The query with `q IS NULL` above also fails before this PR, and returns no row after it under whole-stage codegen.

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

Generated-by: Claude Opus 5.5

Closes #60646 from dongjoon-hyun/SPARK-61924.

Authored-by: Dongjoon Hyun <dongjoon@apache.org>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>

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

skip-checks: true
dongjoon-hyun added a commit that referenced this pull request Nov 18, 2026
… column that can fail through a limit, a sort, a join or an aggregate

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

This PR extends `PredicateHelper.failableOutput`, which #60574 (SPARK-61823) added, so that it also finds the columns that can fail when they reach a `Filter` through a `LIMIT`, an `OFFSET`, a sort that the physical plan removes or a join, or when they are the result of an aggregation. `InferFiltersFromConstraints` then stops putting an inferred filter over such a column, e.g. `q > 0` from `q = k AND k > 0`, ahead of the condition of the `Filter`.

`failableOutput` returns the columns of a plan that can fail to compute. Before this PR, these were the deterministic columns of a `Project` whose expression `ExprUtils.canEvaluateUnconditionally` rejects, looking through `Filter` and `Sample` only. Every other operator returned no column. Under whole-stage codegen, however, the limits, a sort that the physical plan removes and the streamed side of a broadcast hash join hand a column of the `Project` below them on without computing it, and an aggregation computes a deterministic result column only when a filter above first reads it. So an inferred filter over such a column still computes it on rows that a conjunct of the condition drops.

This PR adds the following to the helper:

- `LocalLimit`, `GlobalLimit` and `Offset` pass the columns of their child through, as `Filter` and `Sample` do. A global limit or an offset hands them on lazily only when its input has a single partition. Otherwise, the `Exchange SinglePartition` below it computes every column, and the query fails with `spark.sql.constraintPropagation.enabled=false` too, so this is conservative there.
- `Sort` passes the columns of its child through. When the child already has the ordering, e.g. `range` sorted by `id`, `RemoveRedundantSorts` removes the `SortExec`, and the `Filter` reads the column from the `Project` below. Otherwise, the sort computes every column, and the query fails with `spark.sql.constraintPropagation.enabled=false` too, so this is conservative there.
- `Join` passes the columns of both sides through. Only the streamed side of a broadcast hash join hands them on lazily; a build side, a shuffled hash join or a sort-merge join gets every column computed. The logical plan does not tell them apart, so this is conservative there.
- `Aggregate` returns a result column whose expression, with each aggregate function taken as its value, is deterministic and rejected by `ExprUtils.canEvaluateUnconditionally`, e.g. `10L / (max(id) - 3)`. The aggregation computes its grouping keys and aggregate functions on every row, and a non-deterministic result for every group, so they do not count. Only an aggregation with grouping keys under whole-stage codegen computes such a result column lazily, so this is conservative for a global aggregation or an `ObjectHashAggregateExec`.

The other operators are still not looked through. I checked each of them on the master branch with a query of the same shape, in ANSI mode with whole-stage codegen:

| Operator | Why it is not looked through |
|---|---|
| `SubqueryAlias`, `ResolvedHint` | `FinishAnalysis` removes them before `InferFiltersFromConstraints` runs. |
| `Repartition`, `RepartitionByExpression`, `Window` | The filter is pushed below them. Otherwise, an exchange or `WindowExec` gets every column of every row computed. |
| `Union`, `Generate`, `Deduplicate` | The query fails with `spark.sql.constraintPropagation.enabled=false` too, so an inferred filter does not cause the failure. |
| `Tail` | Only at the top of a plan, from `Dataset.tail`. |

The helper is also used by `CombineFilters` since #60631 (SPARK-61886) and by `PushPredicateThroughJoin` since #60646 (SPARK-61924), so they get the same coverage. For example, `CombineFilters` keeps `q > 0` in the outer filter of `Filter(rand() > 0.1 AND q > 0, Filter(c, Limit(Project(10L / (id - 3) AS q, ...))))` instead of moving it ahead of `rand() > 0.1`, and `PushPredicateThroughJoin` keeps it above the joins in `Filter(rand() > 0.1 AND q > 0, Join(Join(Project(a / b AS q, ...), r), s))` instead of pushing it below them.

### Why are the changes needed?

A query that should succeed fails. With ANSI mode, the default since Apache Spark 4.0.0, a division or a cast is enough.

```sql
-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id FROM (
  SELECT id, 10L / (id - 3) AS q, CAST(id AS DOUBLE) AS k FROM range(0, 10, 1, 1) LIMIT 8)
WHERE id > 5 AND q = k AND k > 0;

-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id FROM (
  SELECT id, max(id) AS m, 10L / (max(id) - 3) AS q, CAST(max(id) AS DOUBLE) AS k
  FROM range(0, 10, 1, 1) GROUP BY id)
WHERE m > 5 AND q = k AND k > 0;

-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id, r >= 0 FROM (
  SELECT /*+ BROADCAST(b) */ id, q, k, rand(2) AS r
  FROM (SELECT id, 10L / (id - 3) AS q, CAST(id AS DOUBLE) AS k FROM range(0, 10, 1, 1)) a
  JOIN (SELECT id AS j FROM range(0, 10, 1, 1)) b ON id = j)
WHERE id > 5 AND q = k AND k > 0;

-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id, r >= 0 FROM (
  SELECT id, q, k, rand(2) AS r FROM (
    SELECT id, 10L / (id - 3) AS q, CAST(id AS DOUBLE) AS k FROM range(0, 10, 1, 1) ORDER BY id))
WHERE id > 5 AND q = k AND k > 0;
```

In each query, the condition written first (`id > 5` or `m > 5`) is false for the row or group where `q` divides by zero, so `q` should never be computed there. The `LIMIT`, the aggregation, and `rand(2) AS r` above the join or the sort keep the condition above the column. In the last query, `range` already outputs `id` in order, so the executed plan has no sort. For the first query, the optimized plan on the master branch is:

```
Project [id#2L]
+- Filter ((((cast(id#2L as double) <=> q#0) AND (q#0 > 0.0)) AND isnotnull(q#0)) AND (((id#2L > 5) AND (q#0 = k#1)) AND (k#1 > 0.0)))
   +- GlobalLimit 8
      +- LocalLimit 8
         +- Project [id#2L, (10.0 / cast((id#2L - 3) as double)) AS q#0, cast(id#2L as double) AS k#1]
            +- Range (0, 10, step=1, splits=Some(1))
```

With this PR, the `Filter` keeps only the written condition. Each query also succeeds with `spark.sql.constraintPropagation.enabled=false`.

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

Yes. The queries above succeed. I confirmed that each of them fails with `DIVIDE_BY_ZERO` in ANSI mode on the released [v3.5.9](https://github.com/apache/spark/releases/tag/v3.5.9) (2026-07-12), [v4.0.5](https://github.com/apache/spark/releases/tag/v4.0.5) (2026-10-21) and [v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) (2026-10-27), and succeeds there with `spark.sql.constraintPropagation.enabled=false`.

When a `Filter` reads such a column through one of these operators, it no longer gets an inferred filter over that column, e.g. `q > 0` or `cast(id as double) <=> q`.

### How was this patch tested?

Pass the CIs with the newly added test cases. Both fail without this PR.

- `InferFiltersFromConstraintsSuite`: no constraint over an ANSI cast column is inferred when the column reaches the `Filter` through a sort, a `LIMIT`, an `OFFSET` and the left side of a join, nor over an aggregate result on the right side whose expression can fail. Constraints over a plain column, a grouping key, an aggregate function result, and a non-deterministic aggregate result are still inferred.
- `DataFrameSuite`: the four queries above, written with the DataFrame API, return no row in ANSI mode with whole-stage codegen instead of failing with `DIVIDE_BY_ZERO`.

I also ran the catalyst optimizer suites, `DataFrameSuite` and the `PlanStabilitySuite`s locally. No golden files change. With a temporary suite (not included), I ran the queries above with whole-stage codegen on and off. Without whole-stage codegen they still fail, before and after this PR, because the interpreted `ProjectExec` and aggregation compute every column of a row.

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

Generated-by: Claude Opus 5.5

Closes #60643 from dongjoon-hyun/SPARK-61921.

Authored-by: Dongjoon Hyun <dongjoon@apache.org>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>


skip-checks: true
dongjoon-hyun added a commit that referenced this pull request Nov 18, 2026
… column that can fail through a limit, a sort, a join or an aggregate

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

This PR extends `PredicateHelper.failableOutput`, which #60574 (SPARK-61823) added, so that it also finds the columns that can fail when they reach a `Filter` through a `LIMIT`, an `OFFSET`, a sort that the physical plan removes or a join, or when they are the result of an aggregation. `InferFiltersFromConstraints` then stops putting an inferred filter over such a column, e.g. `q > 0` from `q = k AND k > 0`, ahead of the condition of the `Filter`.

`failableOutput` returns the columns of a plan that can fail to compute. Before this PR, these were the deterministic columns of a `Project` whose expression `ExprUtils.canEvaluateUnconditionally` rejects, looking through `Filter` and `Sample` only. Every other operator returned no column. Under whole-stage codegen, however, the limits, a sort that the physical plan removes and the streamed side of a broadcast hash join hand a column of the `Project` below them on without computing it, and an aggregation computes a deterministic result column only when a filter above first reads it. So an inferred filter over such a column still computes it on rows that a conjunct of the condition drops.

This PR adds the following to the helper:

- `LocalLimit`, `GlobalLimit` and `Offset` pass the columns of their child through, as `Filter` and `Sample` do. A global limit or an offset hands them on lazily only when its input has a single partition. Otherwise, the `Exchange SinglePartition` below it computes every column, and the query fails with `spark.sql.constraintPropagation.enabled=false` too, so this is conservative there.
- `Sort` passes the columns of its child through. When the child already has the ordering, e.g. `range` sorted by `id`, `RemoveRedundantSorts` removes the `SortExec`, and the `Filter` reads the column from the `Project` below. Otherwise, the sort computes every column, and the query fails with `spark.sql.constraintPropagation.enabled=false` too, so this is conservative there.
- `Join` passes the columns of both sides through. Only the streamed side of a broadcast hash join hands them on lazily; a build side, a shuffled hash join or a sort-merge join gets every column computed. The logical plan does not tell them apart, so this is conservative there.
- `Aggregate` returns a result column whose expression, with each aggregate function taken as its value, is deterministic and rejected by `ExprUtils.canEvaluateUnconditionally`, e.g. `10L / (max(id) - 3)`. The aggregation computes its grouping keys and aggregate functions on every row, and a non-deterministic result for every group, so they do not count. Only an aggregation with grouping keys under whole-stage codegen computes such a result column lazily, so this is conservative for a global aggregation or an `ObjectHashAggregateExec`.

The other operators are still not looked through. I checked each of them on the master branch with a query of the same shape, in ANSI mode with whole-stage codegen:

| Operator | Why it is not looked through |
|---|---|
| `SubqueryAlias`, `ResolvedHint` | `FinishAnalysis` removes them before `InferFiltersFromConstraints` runs. |
| `Repartition`, `RepartitionByExpression`, `Window` | The filter is pushed below them. Otherwise, an exchange or `WindowExec` gets every column of every row computed. |
| `Union`, `Generate`, `Deduplicate` | The query fails with `spark.sql.constraintPropagation.enabled=false` too, so an inferred filter does not cause the failure. |
| `Tail` | Only at the top of a plan, from `Dataset.tail`. |

The helper is also used by `CombineFilters` since #60631 (SPARK-61886) and by `PushPredicateThroughJoin` since #60646 (SPARK-61924), so they get the same coverage. For example, `CombineFilters` keeps `q > 0` in the outer filter of `Filter(rand() > 0.1 AND q > 0, Filter(c, Limit(Project(10L / (id - 3) AS q, ...))))` instead of moving it ahead of `rand() > 0.1`, and `PushPredicateThroughJoin` keeps it above the joins in `Filter(rand() > 0.1 AND q > 0, Join(Join(Project(a / b AS q, ...), r), s))` instead of pushing it below them.

### Why are the changes needed?

A query that should succeed fails. With ANSI mode, the default since Apache Spark 4.0.0, a division or a cast is enough.

```sql
-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id FROM (
  SELECT id, 10L / (id - 3) AS q, CAST(id AS DOUBLE) AS k FROM range(0, 10, 1, 1) LIMIT 8)
WHERE id > 5 AND q = k AND k > 0;

-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id FROM (
  SELECT id, max(id) AS m, 10L / (max(id) - 3) AS q, CAST(max(id) AS DOUBLE) AS k
  FROM range(0, 10, 1, 1) GROUP BY id)
WHERE m > 5 AND q = k AND k > 0;

-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id, r >= 0 FROM (
  SELECT /*+ BROADCAST(b) */ id, q, k, rand(2) AS r
  FROM (SELECT id, 10L / (id - 3) AS q, CAST(id AS DOUBLE) AS k FROM range(0, 10, 1, 1)) a
  JOIN (SELECT id AS j FROM range(0, 10, 1, 1)) b ON id = j)
WHERE id > 5 AND q = k AND k > 0;

-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id, r >= 0 FROM (
  SELECT id, q, k, rand(2) AS r FROM (
    SELECT id, 10L / (id - 3) AS q, CAST(id AS DOUBLE) AS k FROM range(0, 10, 1, 1) ORDER BY id))
WHERE id > 5 AND q = k AND k > 0;
```

In each query, the condition written first (`id > 5` or `m > 5`) is false for the row or group where `q` divides by zero, so `q` should never be computed there. The `LIMIT`, the aggregation, and `rand(2) AS r` above the join or the sort keep the condition above the column. In the last query, `range` already outputs `id` in order, so the executed plan has no sort. For the first query, the optimized plan on the master branch is:

```
Project [id#2L]
+- Filter ((((cast(id#2L as double) <=> q#0) AND (q#0 > 0.0)) AND isnotnull(q#0)) AND (((id#2L > 5) AND (q#0 = k#1)) AND (k#1 > 0.0)))
   +- GlobalLimit 8
      +- LocalLimit 8
         +- Project [id#2L, (10.0 / cast((id#2L - 3) as double)) AS q#0, cast(id#2L as double) AS k#1]
            +- Range (0, 10, step=1, splits=Some(1))
```

With this PR, the `Filter` keeps only the written condition. Each query also succeeds with `spark.sql.constraintPropagation.enabled=false`.

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

Yes. The queries above succeed. I confirmed that each of them fails with `DIVIDE_BY_ZERO` in ANSI mode on the released [v3.5.9](https://github.com/apache/spark/releases/tag/v3.5.9) (2026-07-12), [v4.0.5](https://github.com/apache/spark/releases/tag/v4.0.5) (2026-10-21) and [v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) (2026-10-27), and succeeds there with `spark.sql.constraintPropagation.enabled=false`.

When a `Filter` reads such a column through one of these operators, it no longer gets an inferred filter over that column, e.g. `q > 0` or `cast(id as double) <=> q`.

### How was this patch tested?

Pass the CIs with the newly added test cases. Both fail without this PR.

- `InferFiltersFromConstraintsSuite`: no constraint over an ANSI cast column is inferred when the column reaches the `Filter` through a sort, a `LIMIT`, an `OFFSET` and the left side of a join, nor over an aggregate result on the right side whose expression can fail. Constraints over a plain column, a grouping key, an aggregate function result, and a non-deterministic aggregate result are still inferred.
- `DataFrameSuite`: the four queries above, written with the DataFrame API, return no row in ANSI mode with whole-stage codegen instead of failing with `DIVIDE_BY_ZERO`.

I also ran the catalyst optimizer suites, `DataFrameSuite` and the `PlanStabilitySuite`s locally. No golden files change. With a temporary suite (not included), I ran the queries above with whole-stage codegen on and off. Without whole-stage codegen they still fail, before and after this PR, because the interpreted `ProjectExec` and aggregation compute every column of a row.

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

Generated-by: Claude Opus 5.5

Closes #60643 from dongjoon-hyun/SPARK-61921.

Authored-by: Dongjoon Hyun <dongjoon@apache.org>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>

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


skip-checks: true
dongjoon-hyun added a commit that referenced this pull request Nov 18, 2026
… column that can fail through a limit, a sort, a join or an aggregate

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

This PR extends `PredicateHelper.failableOutput`, which #60574 (SPARK-61823) added, so that it also finds the columns that can fail when they reach a `Filter` through a `LIMIT`, an `OFFSET`, a sort that the physical plan removes or a join, or when they are the result of an aggregation. `InferFiltersFromConstraints` then stops putting an inferred filter over such a column, e.g. `q > 0` from `q = k AND k > 0`, ahead of the condition of the `Filter`.

`failableOutput` returns the columns of a plan that can fail to compute. Before this PR, these were the deterministic columns of a `Project` whose expression `ExprUtils.canEvaluateUnconditionally` rejects, looking through `Filter` and `Sample` only. Every other operator returned no column. Under whole-stage codegen, however, the limits, a sort that the physical plan removes and the streamed side of a broadcast hash join hand a column of the `Project` below them on without computing it, and an aggregation computes a deterministic result column only when a filter above first reads it. So an inferred filter over such a column still computes it on rows that a conjunct of the condition drops.

This PR adds the following to the helper:

- `LocalLimit`, `GlobalLimit` and `Offset` pass the columns of their child through, as `Filter` and `Sample` do. A global limit or an offset hands them on lazily only when its input has a single partition. Otherwise, the `Exchange SinglePartition` below it computes every column, and the query fails with `spark.sql.constraintPropagation.enabled=false` too, so this is conservative there.
- `Sort` passes the columns of its child through. When the child already has the ordering, e.g. `range` sorted by `id`, `RemoveRedundantSorts` removes the `SortExec`, and the `Filter` reads the column from the `Project` below. Otherwise, the sort computes every column, and the query fails with `spark.sql.constraintPropagation.enabled=false` too, so this is conservative there.
- `Join` passes the columns of both sides through. Only the streamed side of a broadcast hash join hands them on lazily; a build side, a shuffled hash join or a sort-merge join gets every column computed. The logical plan does not tell them apart, so this is conservative there.
- `Aggregate` returns a result column whose expression, with each aggregate function taken as its value, is deterministic and rejected by `ExprUtils.canEvaluateUnconditionally`, e.g. `10L / (max(id) - 3)`. The aggregation computes its grouping keys and aggregate functions on every row, and a non-deterministic result for every group, so they do not count. Only an aggregation with grouping keys under whole-stage codegen computes such a result column lazily, so this is conservative for a global aggregation or an `ObjectHashAggregateExec`.

The other operators are still not looked through. I checked each of them on the master branch with a query of the same shape, in ANSI mode with whole-stage codegen:

| Operator | Why it is not looked through |
|---|---|
| `SubqueryAlias`, `ResolvedHint` | `FinishAnalysis` removes them before `InferFiltersFromConstraints` runs. |
| `Repartition`, `RepartitionByExpression`, `Window` | The filter is pushed below them. Otherwise, an exchange or `WindowExec` gets every column of every row computed. |
| `Union`, `Generate`, `Deduplicate` | The query fails with `spark.sql.constraintPropagation.enabled=false` too, so an inferred filter does not cause the failure. |
| `Tail` | Only at the top of a plan, from `Dataset.tail`. |

The helper is also used by `CombineFilters` since #60631 (SPARK-61886) and by `PushPredicateThroughJoin` since #60646 (SPARK-61924), so they get the same coverage. For example, `CombineFilters` keeps `q > 0` in the outer filter of `Filter(rand() > 0.1 AND q > 0, Filter(c, Limit(Project(10L / (id - 3) AS q, ...))))` instead of moving it ahead of `rand() > 0.1`, and `PushPredicateThroughJoin` keeps it above the joins in `Filter(rand() > 0.1 AND q > 0, Join(Join(Project(a / b AS q, ...), r), s))` instead of pushing it below them.

### Why are the changes needed?

A query that should succeed fails. With ANSI mode, the default since Apache Spark 4.0.0, a division or a cast is enough.

```sql
-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id FROM (
  SELECT id, 10L / (id - 3) AS q, CAST(id AS DOUBLE) AS k FROM range(0, 10, 1, 1) LIMIT 8)
WHERE id > 5 AND q = k AND k > 0;

-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id FROM (
  SELECT id, max(id) AS m, 10L / (max(id) - 3) AS q, CAST(max(id) AS DOUBLE) AS k
  FROM range(0, 10, 1, 1) GROUP BY id)
WHERE m > 5 AND q = k AND k > 0;

-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id, r >= 0 FROM (
  SELECT /*+ BROADCAST(b) */ id, q, k, rand(2) AS r
  FROM (SELECT id, 10L / (id - 3) AS q, CAST(id AS DOUBLE) AS k FROM range(0, 10, 1, 1)) a
  JOIN (SELECT id AS j FROM range(0, 10, 1, 1)) b ON id = j)
WHERE id > 5 AND q = k AND k > 0;

-- It should return no row, but fails with DIVIDE_BY_ZERO.
SELECT id, r >= 0 FROM (
  SELECT id, q, k, rand(2) AS r FROM (
    SELECT id, 10L / (id - 3) AS q, CAST(id AS DOUBLE) AS k FROM range(0, 10, 1, 1) ORDER BY id))
WHERE id > 5 AND q = k AND k > 0;
```

In each query, the condition written first (`id > 5` or `m > 5`) is false for the row or group where `q` divides by zero, so `q` should never be computed there. The `LIMIT`, the aggregation, and `rand(2) AS r` above the join or the sort keep the condition above the column. In the last query, `range` already outputs `id` in order, so the executed plan has no sort. For the first query, the optimized plan on the master branch is:

```
Project [id#2L]
+- Filter ((((cast(id#2L as double) <=> q#0) AND (q#0 > 0.0)) AND isnotnull(q#0)) AND (((id#2L > 5) AND (q#0 = k#1)) AND (k#1 > 0.0)))
   +- GlobalLimit 8
      +- LocalLimit 8
         +- Project [id#2L, (10.0 / cast((id#2L - 3) as double)) AS q#0, cast(id#2L as double) AS k#1]
            +- Range (0, 10, step=1, splits=Some(1))
```

With this PR, the `Filter` keeps only the written condition. Each query also succeeds with `spark.sql.constraintPropagation.enabled=false`.

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

Yes. The queries above succeed. I confirmed that each of them fails with `DIVIDE_BY_ZERO` in ANSI mode on the released [v3.5.9](https://github.com/apache/spark/releases/tag/v3.5.9) (2026-07-12), [v4.0.5](https://github.com/apache/spark/releases/tag/v4.0.5) (2026-10-21) and [v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0) (2026-10-27), and succeeds there with `spark.sql.constraintPropagation.enabled=false`.

When a `Filter` reads such a column through one of these operators, it no longer gets an inferred filter over that column, e.g. `q > 0` or `cast(id as double) <=> q`.

### How was this patch tested?

Pass the CIs with the newly added test cases. Both fail without this PR.

- `InferFiltersFromConstraintsSuite`: no constraint over an ANSI cast column is inferred when the column reaches the `Filter` through a sort, a `LIMIT`, an `OFFSET` and the left side of a join, nor over an aggregate result on the right side whose expression can fail. Constraints over a plain column, a grouping key, an aggregate function result, and a non-deterministic aggregate result are still inferred.
- `DataFrameSuite`: the four queries above, written with the DataFrame API, return no row in ANSI mode with whole-stage codegen instead of failing with `DIVIDE_BY_ZERO`.

I also ran the catalyst optimizer suites, `DataFrameSuite` and the `PlanStabilitySuite`s locally. No golden files change. With a temporary suite (not included), I ran the queries above with whole-stage codegen on and off. Without whole-stage codegen they still fail, before and after this PR, because the interpreted `ProjectExec` and aggregation compute every column of a row.

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

Generated-by: Claude Opus 5.5

Closes #60643 from dongjoon-hyun/SPARK-61921.

Authored-by: Dongjoon Hyun <dongjoon@apache.org>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>

(cherry picked from commit 53b78a9)
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>
dongjoon-hyun added a commit that referenced this pull request Nov 19, 2026
### What changes were proposed in this pull request?

This PR aims to make `CombineFilters` use `PredicateHelper.splitMovable`, which SPARK-61930 (#60677) added, instead of doing the same split of the outer filter condition inline.

```scala
val (movable, rest) = splitMovable(splitConjunctivePredicates(fc), Seq(grandChild))
```

`CombineFilters` has split the outer condition inline since SPARK-60980 (#60157) and SPARK-61886 (#60631): it combines the conjuncts up to the first non-deterministic or throwable one, and the later conjuncts that `ExprUtils.canEvaluateUnconditionally` accepts and that read no column of `grandChild` that can fail (`failableOutput`), into the filter below. `splitMovable` does exactly this for `plans = Seq(grandChild)`.

This PR also updates the Scaladoc of `splitMovable` to mention combining into the filter below, and the comment of `CombineFilters` to point to `splitMovable`.

### Why are the changes needed?

To keep a single implementation of the rule that decides which conjuncts may be evaluated ahead of the others, shared by `CombineFilters`, `PushPredicateThroughJoin` and `ReorderJoin`.

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

No. This is a refactoring without any behavior change.

### How was this patch tested?

Pass the CIs with the existing tests, which cover this code path.
- `FilterPushdownSuite`: `SPARK-60980` and `SPARK-61886` test cases
- `DataFrameSuite`: `SPARK-60980` and `SPARK-61886` test cases

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

Generated-by: Claude Opus 5.5

Closes #60692 from dongjoon-hyun/SPARK-62049.

Authored-by: Dongjoon Hyun <dongjoon@apache.org>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>


skip-checks: true
dongjoon-hyun added a commit that referenced this pull request Nov 19, 2026
### What changes were proposed in this pull request?

This PR aims to make `CombineFilters` use `PredicateHelper.splitMovable`, which SPARK-61930 (#60677) added, instead of doing the same split of the outer filter condition inline.

```scala
val (movable, rest) = splitMovable(splitConjunctivePredicates(fc), Seq(grandChild))
```

`CombineFilters` has split the outer condition inline since SPARK-60980 (#60157) and SPARK-61886 (#60631): it combines the conjuncts up to the first non-deterministic or throwable one, and the later conjuncts that `ExprUtils.canEvaluateUnconditionally` accepts and that read no column of `grandChild` that can fail (`failableOutput`), into the filter below. `splitMovable` does exactly this for `plans = Seq(grandChild)`.

This PR also updates the Scaladoc of `splitMovable` to mention combining into the filter below, and the comment of `CombineFilters` to point to `splitMovable`.

### Why are the changes needed?

To keep a single implementation of the rule that decides which conjuncts may be evaluated ahead of the others, shared by `CombineFilters`, `PushPredicateThroughJoin` and `ReorderJoin`.

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

No. This is a refactoring without any behavior change.

### How was this patch tested?

Pass the CIs with the existing tests, which cover this code path.
- `FilterPushdownSuite`: `SPARK-60980` and `SPARK-61886` test cases
- `DataFrameSuite`: `SPARK-60980` and `SPARK-61886` test cases

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

Generated-by: Claude Opus 5.5

Closes #60692 from dongjoon-hyun/SPARK-62049.

Authored-by: Dongjoon Hyun <dongjoon@apache.org>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>

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


skip-checks: true
dongjoon-hyun added a commit that referenced this pull request Nov 19, 2026
### What changes were proposed in this pull request?

This PR aims to make `CombineFilters` use `PredicateHelper.splitMovable`, which SPARK-61930 (#60677) added, instead of doing the same split of the outer filter condition inline.

```scala
val (movable, rest) = splitMovable(splitConjunctivePredicates(fc), Seq(grandChild))
```

`CombineFilters` has split the outer condition inline since SPARK-60980 (#60157) and SPARK-61886 (#60631): it combines the conjuncts up to the first non-deterministic or throwable one, and the later conjuncts that `ExprUtils.canEvaluateUnconditionally` accepts and that read no column of `grandChild` that can fail (`failableOutput`), into the filter below. `splitMovable` does exactly this for `plans = Seq(grandChild)`.

This PR also updates the Scaladoc of `splitMovable` to mention combining into the filter below, and the comment of `CombineFilters` to point to `splitMovable`.

### Why are the changes needed?

To keep a single implementation of the rule that decides which conjuncts may be evaluated ahead of the others, shared by `CombineFilters`, `PushPredicateThroughJoin` and `ReorderJoin`.

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

No. This is a refactoring without any behavior change.

### How was this patch tested?

Pass the CIs with the existing tests, which cover this code path.
- `FilterPushdownSuite`: `SPARK-60980` and `SPARK-61886` test cases
- `DataFrameSuite`: `SPARK-60980` and `SPARK-61886` test cases

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

Generated-by: Claude Opus 5.5

Closes #60692 from dongjoon-hyun/SPARK-62049.

Authored-by: Dongjoon Hyun <dongjoon@apache.org>
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>

(cherry picked from commit 3c0a393)
Signed-off-by: Dongjoon Hyun <dongjoon@apache.org>
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.

4 participants