spark-test commented on code in PR #60574:
URL: https://github.com/apache/spark/pull/60574#discussion_r4594843198


##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala:
##########
@@ -3075,6 +3075,21 @@ class DataFrameSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61823: an inferred filter over a column that can fail is not 
evaluated " +
+    "ahead of the condition") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // `id > 5` keeps `q`, a division by zero on id 3, from being evaluated, 
unless a filter
+      // `q > 0` inferred from `q = k AND k > 0` goes ahead of it. The 
non-deterministic `r` keeps
+      // the condition above the projection.

Review Comment:
   **Nit (P3):** This expectation holds only under whole-stage codegen. Reading 
the code, with spark.sql.codegen.wholeStage=false the interpreted ProjectExec 
computes `10L / (id - 3)` for id 3 before the filter runs, so `checkAnswer(df, 
Nil)` fails with DIVIDE_BY_ZERO even with the fix, as the PR description says. 
The test passes today only because codegen is on by default. Pinning it, as the 
SPARK-60602 and SPARK-60633 tests above do, and saying why in the comment keeps 
the test meaningful under any default:
   
   ```suggestion
       withSQLConf(
         SQLConf.ANSI_ENABLED.key -> "true",
         SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true") {
         // `id > 5` keeps `q`, a division by zero on id 3, from being 
evaluated, unless a filter
         // `q > 0` inferred from `q = k AND k > 0` goes ahead of it. The 
non-deterministic `r` keeps
         // the condition above the projection. Only whole-stage codegen defers 
`q` past the filter:
         // an interpreted projection computes every column, so the query fails 
without it.
   ```
   
   **Verification:**
   - **Behavior:** With the session default of whole-stage codegen set to 
false, the test still runs its query with whole-stage codegen and returns no 
row.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2314,11 +2314,16 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
   private def inferFilters(
       plan: LogicalPlan, acrossAsOfJoins: Boolean): LogicalPlan = 
plan.transformWithPruning(
     _.containsAnyPattern(FILTER, JOIN, AS_OF_JOIN)) {
+    // The new filters go ahead of the condition, so one over a column that 
can fail (see
+    // `failableOutput`) would compute that column on rows a conjunct of the 
condition drops.
     case filter @ Filter(condition, child) =>
       val canAdd: Expression => Boolean =
         if (filter.getTagValue(asOfInputFilterTag).isDefined) canBeAsOfFilter 
else canBeFilter
+      lazy val failable = failableOutput(child)
       val newFilters = (filter.constraints --
-        (child.constraints ++ 
splitConjunctivePredicates(condition))).toSeq.filter(canAdd)
+        (child.constraints ++ 
splitConjunctivePredicates(condition))).toSeq.filter { c =>
+          canAdd(c) && !c.references.exists(failable.contains)

Review Comment:
   **Non-blocking (P2):** This check runs whatever 
spark.sql.legacy.inferFailableFiltersFromConstraints is set to, because the 
flag is read only inside `canBeFilter`. With the flag true, the description's 
example still loses `cast(id as double) <=> q`, `q > 0` and `isnotnull(q)`, 
which the base branch and released 4.3.0 infer, while the flag's doc says the 
flag restores filters whose evaluation can fail and the 4.4 migration entry 
says plain comparisons are still inferred by default. Because this change can 
drop pushdown and partition pruning that released versions apply, users need 
that rollback. Applying the check only when the flag is false, or when the 
Filter carries the as-of input tag, since an as-of input gets no failable 
filter even with the flag on, would restore it, for example:
   
   ```scala
   val excludeFailable = !conf.legacyInferFailableFiltersFromConstraints ||
     filter.getTagValue(asOfInputFilterTag).isDefined
   ...
   canAdd(c) && !(excludeFailable && c.references.exists(failable.contains))
   ```
   
   The flag's doc and the 4.4 migration entry would then also need to cover 
filters over a column computed with an expression that can fail, and a 
legacy-mode test over a failable projected column would pin it down; the 
existing legacy-mode case filters a bare LocalRelation, where the new helper 
returns nothing.
   
   **Verification:**
   - **Regression:** With the legacy flag true, a Filter kept above a Project 
with an ANSI-cast column infers the same filters as on the base branch, 
including a comparison and an IS NOT NULL over the failable column.
   - **Compatibility:** With the legacy flag true, a tagged as-of input Filter 
over a Project with a failable column still gets no inferred filter over that 
column.
   - **Inspection:** The flag's doc and the 4.4 migration entry name filters 
over a column computed with an expression that can fail, say that they are not 
inferred by default, and say that the flag restores them.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -230,6 +230,30 @@ trait PredicateHelper extends AliasHelper with Logging {
     case e => e.children.forall(canEvaluateWithinJoin)
   }
 
+  /**
+   * The output columns of `plan` that can fail to compute: the deterministic 
columns of a
+   * [[Project]] whose expression [[ExprUtils.canEvaluateUnconditionally]] 
rejects or reads such a
+   * column of its child, looking through [[Filter]] and [[Sample]]. A 
condition over such a column
+   * can fail as its expression does: under whole-stage codegen, the 
projection computes a
+   * deterministic column for a row only when a condition above first reads 
it, and
+   * `PushPredicateThroughNonJoin` pushes a condition below the projection 
with the expression
+   * substituted. A non-deterministic column is computed on every row the 
projection gets, so it
+   * does not count. Other operators are not looked through.
+   */
+  protected def failableOutput(plan: LogicalPlan): AttributeSet = plan match {
+    case Project(projectList, child) =>
+      val below = failableOutput(child)
+      AttributeSet(projectList.collect {
+        case a: Alias if a.child.deterministic &&
+            (!ExprUtils.canEvaluateUnconditionally(a.child) ||
+              a.child.references.exists(below.contains)) => a.toAttribute
+        case a: Attribute if below.contains(a) => a
+      })
+    case Filter(_, child) => failableOutput(child)
+    case s: Sample => failableOutput(s.child)
+    case _ => AttributeSet.empty

Review Comment:
   **Non-blocking (P2):** Reading the code, this catch-all leaves the failure 
in place whenever the failable column reaches the Filter, under whole-stage 
codegen, through an operator other than Project, Filter or Sample that also 
lets codegen defer it. For example, in ANSI mode, `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`: the limits pass the Project's constraints up 
and no filter is pushed through a limit, so the Filter case still infers 
`cast(id as double) <=> q` and `q > 0` ahead of `id > 5`. The single-slice 
range needs no exchange under GlobalLimitExec and BaseLimitExec.usedInputs is 
empty, so `q` is still computed only when the FilterExec first reads it, which 
is now on id 3, where it divides by zero. OFFSET is planned as GlobalLimitExec 
too. The same holds for a grouped aggregate's result column, because 
HashAggregateExec and SortAggregateExec evaluate only the non-deterministic res
 ult expressions before handing a row on (the SPARK-60633 aggregateAliasQuery 
test relies on that), and for a failable column on the streamed side of a 
broadcast hash join under a Project with `rand()`. These are traced examples 
rather than a complete list, and no comment marks them as deferred.
   
   **Recommended change:** Change the fallback of `failableOutput` from no 
columns to the failable columns the operator forwards. LocalLimit, GlobalLimit, 
Offset, Join, Generate and any other operator that outputs a child's column 
unchanged report that column as failable when the child does, and a Union 
reports a column when some child's column at that position is failable. Only 
leaves, Sort, Window and the repartitioning operators, which compute every 
input column before handing rows on, report none. Add an Aggregate case that 
reports the result columns whose expression, with each aggregate function taken 
as its value, `ExprUtils.canEvaluateUnconditionally` rejects, but not the 
grouping keys, which the aggregation computes for every input row. Update the 
helper's doc comment, which now says that other operators are not looked 
through; the PR description's sentence saying the same needs the same 
correction. Add optimizer rule tests and end-to-end ANSI tests for the new 
shapes.
   
   **Why this works:** The Filter case already drops any inferred constraint 
that reads a column `failableOutput(child)` returns. Once the helper reports 
every failable column that can reach the Filter still deferred, whether 
forwarded by an operator or computed lazily as an Aggregate result, no inferred 
filter can compute such a column ahead of the condition, whichever operator 
sits between them.
   
   **Scope:** Widen the failable-column helper from a Project, Filter and 
Sample whitelist to every operator that forwards a child's column, with 
Aggregate result columns judged by their own expressions, and cover the new 
shapes with tests.
   
   **Compatibility:** Inferred filters over columns that cannot fail, including 
plain pass-through columns and non-deterministic Project columns, are still 
added, and the join and as-of join cases infer the same filters as before.
   
   **Risks:** Filters above limits, offsets, unions, joins, Generate and 
Aggregates with failable result columns lose their inferred filters over 
failable columns. This includes inputs whose condition already computes the 
column first, and forwarding operators whose input is in fact materialized, 
such as the build side of a join. So plans and plan-stability golden files can 
change, although results do not; the legacy flag, once gated, rolls this back. 
The helper's semantics move away from the FailableColumns in #60516 that the 
description says it matches, so a rule that shares it inherits the wider 
coverage. The walk now continues below operators other than Project, Filter and 
Sample until a leaf or a materializing operator, so each Filter's walk can 
visit more of the plan. It is still bounded by the constraint propagation the 
rule runs over the same nodes.
   
   **Constraints:** Keep non-deterministic Project columns not failable, since 
ProjectExec computes them on every row, and keep the alias rule for Project 
columns as it is. An operator the helper does not name must pass its children's 
failable columns up rather than hide them. The legacy-flag gate added by the 
flag repair must apply to the widened set unchanged.
   
   **Exclusions:**
   - The interpreted path, where ProjectExec computes every column and the PR 
declares the failure out of scope.
   - The join and as-of join cases' own inference, which the PR's scope keeps 
as it is.
   - The refinement offered in the decision challenge about safe pushdown, 
which awaits the author's decision.
   
   **Success:** With ANSI mode and whole-stage codegen, the PR's example query 
with `LIMIT 8`, with an OFFSET, with the failable column computed as a grouped 
Aggregate result, or with the column on the streamed side of a broadcast join 
under a Project with `rand()`, returns its rows instead of failing. The Filter 
case adds no inferred filter over a failable column that reaches it through any 
operator other than Sort, Window or a repartitioning operator, nor over an 
Aggregate result column whose expression over the aggregate values can fail. 
Inferred filters over grouping keys, over Aggregate result columns that cannot 
fail, and over columns that reach the Filter through Sort, Window or a 
repartition are still added.
   
   **Verification:**
   - **Regression:** With ANSI mode and whole-stage codegen on, a query whose 
Filter gets a failable column through any operator that hands it up within the 
codegen stage, and whose written condition drops the rows on which that column 
fails, returns the expected rows instead of failing; the cases include the 
description's query with LIMIT, with OFFSET, and through a broadcast join under 
a non-deterministic Project, and a grouped Aggregate whose result column 
divides by zero on a group the condition drops.
   - **Behavior:** At the rule level, a Filter over a failable Project column 
reached through a limit, an offset, a join, a union, a Generate or a forwarding 
operator that the helper does not name, or over an Aggregate result column that 
can fail, gets no inferred filter over that column, while one over a grouping 
key, a total result column, or a column reached through Sort or Window still 
gets its inferred filter.
   - **Compatibility:** TPC-DS and TPC-H plan stability either stays unchanged, 
or every changed plan differs only by dropped inferred filters over columns 
computed with expressions that can fail.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/InferFiltersFromConstraintsSuite.scala:
##########
@@ -449,6 +449,22 @@ class InferFiltersFromConstraintsSuite extends PlanTest {
       Some("l.x".attr === "r.y".attr))
   }
 
+  test("SPARK-61823: a constraint over a column that can fail is not inferred 
as a filter") {
+    // `i` can fail as the cast does, and `j` as it reads `i`, also through 
the sample, the
+    // projection and the filter above them. So no constraint over either, 
e.g. `i > 0` from
+    // `i = k AND k > 0`, goes ahead of the condition, while one over the 
non-deterministic `r`,
+    // which is computed on every row, does.
+    val projected = LocalRelation($"s".string, $"k".int)
+      .select($"k", Cast($"s", IntegerType, evalMode = EvalMode.ANSI).as("i"),

Review Comment:
   **Nit (P3):** Every deterministic alias in this test is failable: `i` is an 
ANSI cast and `j = IsNull(i)` reads it, so the test expects inferred filters 
only on the plain `k` and the non-deterministic `r`. If `failableOutput` 
treated every deterministic alias as failable, for example by losing the 
`canEvaluateUnconditionally` check or ignoring a cast's eval mode, both new 
tests would still pass and only plans would change. An alias the check accepts, 
such as `Cast($"k", LongType)` or this string cast with `EvalMode.LEGACY`, 
carried through the same Sample, Project and Filter chain with a conjunct that 
yields an inferred filter over it, and an expectation for that filter, would 
cover the accept side.
   
   **Verification:**
   - **Behavior:** The Filter case infers a filter over a widening-cast alias 
and over a LEGACY-mode string-to-int cast alias behind the Sample, Project and 
Filter chain, and none over the ANSI cast alias or a column computed from it.
   - **Regression:** With the helper changed to count every deterministic alias 
as failable, the extended rule test fails.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to