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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -274,19 +286,32 @@ trait PredicateHelper extends AliasHelper with Logging {
         case a: Attribute if below.contains(a) => a
       })
     case agg: Aggregate =>
+      val below = failableOutput(agg.child)
       AttributeSet(agg.aggregateExpressions.flatMap {
         case a: Alias =>
           val result = a.child.transform { case e: AggregateExpression => 
e.resultAttribute }
-          if (result.deterministic && 
!ExprUtils.canEvaluateUnconditionally(result)) {
+          if (result.deterministic && 
(!ExprUtils.canEvaluateUnconditionally(result) ||
+              result.references.exists(below.contains))) {
             Some(a.toAttribute)
           } else {
             None
           }
+        case a: Attribute if below.contains(a) => Some(a)
         case _ => None
       })
     case j: Join => failableOutput(j.left) ++ failableOutput(j.right)
-    case _: Filter | _: Sample | _: LocalLimit | _: GlobalLimit | _: Offset | 
_: Sort =>
+    case u: Union =>
+      val children = u.children.map(c => (c.output, failableOutput(c)))
+      AttributeSet(u.output.zipWithIndex.collect {
+        case (a, i) if children.exists { case (output, failable) =>
+          failable.contains(output(i))
+        } => a
+      })
+    case _: Filter | _: Sample | _: LocalLimit | _: GlobalLimit | _: Offset | 
_: Sort |
+         _: Window | _: EventTimeWatermark =>

Review Comment:
   **Blocking (P1):** This case, like the grouping-key and `canPushThrough` 
cases, also feeds `splitMovable` for conjuncts over *both* join inputs. Reading 
the optimizer and planner, for `a.join(c).where(rand() < 0.5 && $"x" === 
$"y")`, where `x` is `$"value".cast("int")` computed below `withWatermark` on a 
stream-stream join, `x = y` now stays in the `Filter` above a `Join` with no 
condition, so `StreamingJoinStrategy` finds no equi-join key and throws 
`streamJoinStreamWithoutEqualityPredicateUnsupportedError` when the first 
micro-batch is planned; on the base branch `x = y` became the join key and the 
query ran. In batch, `SELECT * FROM (SELECT CAST(s AS INT) AS k, count(*) AS c 
FROM t1 GROUP BY CAST(s AS INT)) a, t2 b WHERE rand() < 0.5 AND a.k = b.k` 
loses its equi-join key the same way, since `a.k` is the alias of the grouping 
key that `PullOutGroupingExpressions` pulls out, and becomes a filtered 
nested-loop or cartesian join. A window's exchange, a shuffle, a hash 
aggregation'
 s grouping key and `EventTimeWatermarkExec`, which is not a codegen operator, 
compute the column on every row they get, so evaluating such an equality in the 
join condition cannot fail; only a condition that travels below the operator 
and through the projection can.
   
   **Recommended change:** Make failableOutput in predicates.scala answer 
separately which columns a condition can fail on wherever it is read and which 
it can fail on once it travels below an operator to the projection: the window, 
watermark, repartition-type canPushThrough and grouping-key cases count only 
for the second, while projections, filters, samples, limits, offsets, sorts, 
joins, unions and the other canPushThrough operators, such as Generate and 
Expand, which can pass a lazily computed column on, count for both, and state 
the two answers in its scaladoc. splitMovable then checks a conjunct whose 
columns span more than one of its inputs against the first answer only, and 
every other conjunct, and the Filter case of InferFiltersFromConstraints, 
against the second. Leave a TODO at the join case of 
InferFiltersFromConstraints in Optimizer.scala saying that a filter it infers 
from a conjunct moved into the join condition after a non-deterministic or 
throwable one can still be 
 pushed below one of these operators and through the projection that computes 
its column, where it can fail on rows that the earlier conjunct or a join below 
drops. Add optimizer tests for filters over joins whose sides are these 
operators and a stream-stream join test.
   
   **Why this works:** A window's exchange, a shuffle, a hash aggregation's 
grouping key and the watermark, which is not a codegen operator, compute the 
column on every row they get, so a join condition that reads it cannot fail on 
a row where that operator has not computed it already; only a condition that 
travels below the operator and through the projection can. Checking a conjunct 
over several inputs against the narrower answer lets such an equality into the 
join condition again, so a stream-stream join gets its equi-join key and a 
batch join stays an equi-join, while one-sided conditions keep the full answer 
that the PR's correction needs.
   
   **Compatibility:** One-sided conditions and the Filter case of 
InferFiltersFromConstraints keep using every column the PR now reports, so the 
description's queries still succeed.
   
   **Risks:** A conjunct over both sides that moves into the join condition 
again lets the join case of InferFiltersFromConstraints infer a filter over one 
side from it, which, as on the base branch and as for an equality written in 
the ON clause, can be pushed into a join below the computing projection and 
fail on rows that join drops; queries of that shape, which this PR makes 
succeed by keeping the equality above a join without a condition, fail again as 
they do on the base branch. The change adds no configuration; reverting it 
brings back the PR's current plans for these conjuncts.
   
   **Constraints:** The answer used for conjuncts over several inputs keeps 
reporting through projections, unions, Generate, Expand and the other operators 
that pass a lazily computed column on, as on the base branch. The fixes for the 
watermark's event time, for as-of, lookup and lateral joins and for CTE 
references place each operator in these two answers in the same way.
   
   **Exclusions:**
   - Filters that the join case of InferFiltersFromConstraints infers on a join 
side from a conjunct moved into the join condition after a non-deterministic or 
throwable one can still fail, as on the base branch, on rows that the earlier 
conjunct or a join below the computing projection drops; keeping them out needs 
that rule to tell such a moved conjunct from one written in the ON clause, a 
separate change that the TODO names.
   
   **Verification:**
   - **Regression:** A stream-stream inner join written without an ON clause, 
whose WHERE equality follows rand() and reads a key that an ANSI cast computes 
below withWatermark, plans and returns the joined rows, where it now fails with 
the error for a stream-stream join without an equality predicate.
   - **Regression:** After a non-deterministic conjunct, an equality between a 
join input that is a window, an aggregation grouped by a column that can fail, 
a repartition or a watermark over a projection computing that column, and the 
other input, ends up in the join condition, while a one-sided condition over 
that column, when it is not the watermark's event time, still stays above the 
join.
   - **Compatibility:** After a non-deterministic conjunct, an equality between 
the two inputs that reads a column that a projection directly under the join 
computes with an expression that can fail, or that a union passes on from such 
a projection, still stays above the join, as on the base branch.
   - **Behavior:** The five queries of the PR description still return no row 
in ANSI mode with whole-stage codegen on and off.
   - **Inspection:** A TODO at the join case of InferFiltersFromConstraints 
says that a filter it infers from a conjunct moved into the join condition 
after a non-deterministic or throwable conjunct can still be pushed below these 
operators and fail.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -274,19 +286,32 @@ trait PredicateHelper extends AliasHelper with Logging {
         case a: Attribute if below.contains(a) => a
       })
     case agg: Aggregate =>
+      val below = failableOutput(agg.child)
       AttributeSet(agg.aggregateExpressions.flatMap {
         case a: Alias =>
           val result = a.child.transform { case e: AggregateExpression => 
e.resultAttribute }
-          if (result.deterministic && 
!ExprUtils.canEvaluateUnconditionally(result)) {
+          if (result.deterministic && 
(!ExprUtils.canEvaluateUnconditionally(result) ||
+              result.references.exists(below.contains))) {
             Some(a.toAttribute)
           } else {
             None
           }
+        case a: Attribute if below.contains(a) => Some(a)
         case _ => None
       })
     case j: Join => failableOutput(j.left) ++ failableOutput(j.right)
-    case _: Filter | _: Sample | _: LocalLimit | _: GlobalLimit | _: Offset | 
_: Sort =>
+    case u: Union =>
+      val children = u.children.map(c => (c.output, failableOutput(c)))
+      AttributeSet(u.output.zipWithIndex.collect {
+        case (a, i) if children.exists { case (output, failable) =>
+          failable.contains(output(i))
+        } => a
+      })
+    case _: Filter | _: Sample | _: LocalLimit | _: GlobalLimit | _: Offset | 
_: Sort |
+         _: Window | _: EventTimeWatermark =>

Review Comment:
   **Blocking (P1):** This also passes the watermark's own event-time column 
through, but `PushPredicateThroughNonJoin` never pushes a conjunct that reads 
`watermark.eventTime` below the watermark (`Optimizer.scala` 2984-2987), and 
`EventTimeWatermarkExec` reads that column on every row its child produces, so 
reporting it protects nothing. By my reading of the planner, for 
`a.join(c).where(rand() < 0.5 && $"k" === $"k2" && $"ts" >= $"tc")` with `ts = 
$"s".cast("timestamp")` computed below `withWatermark("ts", ...)`, `k = k2` 
becomes the join key but `ts >= tc` stays in the filter above the join, so 
`StreamingSymmetricHashJoinExec` gets no condition, `getStateValueWatermark` 
returns `None`, and the left side's state is never evicted; the base branch put 
`ts >= tc` in the join condition and evicted it. A `Filter(ts > X)` above the 
watermark also no longer gets `isnotnull(ts)`, so the planned filter stops 
declaring the event time non-nullable, which can change the nullability of the 
eve
 nt time in a stream-stream join's state schema. Leaving `eventTime` out of 
this case, with a comment saying why, avoids all three and keeps the fix intact.
   
   **Verification:**
   - **Behavior:** After rand() in a filter over a join, a condition over a 
watermark's event time that an ANSI cast of a string computes below the 
watermark is pushed into that side, while a condition over another column that 
can fail on that side stays above the join.
   - **Regression:** A Filter with a comparison over such an event time above 
the watermark gets an inferred isnotnull of the event time in the optimized 
plan, and the FilterExec planned for it declares the event time non-nullable in 
its output.
   - **Regression:** A stream-stream inner join whose comparison between the 
two event times is written in WHERE after rand() evicts the bounded side's 
state rows once the other side's watermark passes them, over several 
micro-batches.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -255,12 +258,21 @@ trait PredicateHelper extends AliasHelper with Logging {
    *  - [[Join]], from both sides. Only the streamed side of a broadcast hash 
join passes them
    *    through; a build side, a shuffled hash join or a sort-merge join 
computes every column, so
    *    this is conservative for them.
+   *  - [[Union]], by position: an output column is one when the column of 
some child at its
+   *    position is.
+   *  - [[Window]], [[EventTimeWatermark]] and the operators of
+   *    `PushPredicateThroughNonJoin.canPushThrough`, e.g. `Repartition` and 
`Generate`.
+   * A union outside whole-stage codegen, these other operators and an 
aggregation, for a grouping
+   * key, may compute such a column on every row they get, but 
`PushPredicateThroughNonJoin`
+   * pushes a condition over it below them, and on through the projection that 
computes it with
+   * its expression substituted, e.g. into one side of a join there, where it 
is evaluated on the
+   * rows that the join drops.
    *
    * Other columns and operators do not count:
-   *  - A non-deterministic column, computed for every row the operator 
outputs, and the grouping
-   *    keys and aggregate functions of an aggregation, computed on every row 
it gets.
-   *  - The columns through any other operator, e.g. a `Union`, `Generate`, 
`Deduplicate`,
-   *    `Window` or `Repartition`, whose input rows get every column computed.
+   *  - A non-deterministic column, computed for every row the operator 
outputs, and the
+   *    aggregate functions of an aggregation, computed on every row it gets.
+   *  - The columns through any other operator, e.g. a `Deduplicate` or 
`CollectMetrics`, whose
+   *    input rows get every column computed and that no condition is pushed 
through.

Review Comment:
   **Non-blocking (P2):** This does not hold for a reference to a CTE that 
`InlineCTE` keeps, such as a `MATERIALIZED` one: 
`PushdownPredicatesAndPruneColumnsForCTEDef` collects the deterministic 
conditions over each reference and puts their OR into the definition, where 
`PushDownPredicates` carries them through the definition's projection and into 
a join there. Reading those rules, `WITH c AS MATERIALIZED (SELECT CAST(l.id * 
1000000000 AS INT) AS k FROM range(10) AS l JOIN range(3) AS r ON l.id = r.id) 
SELECT * FROM c CROSS JOIN range(1) WHERE rand(10) * 10 > 100 AND k > 0` still 
moves `k > 0` past the `rand` conjunct onto the reference and from there into 
`l`, failing with `CAST_OVERFLOW` as the description's queries did. 
`failableOutput` would need the CTE definitions to see through a reference, as 
`ConstantPropagation.failableColumnsOf` does.
   
   **Recommended change:** Collect the definitions of the kept CTEs once per 
application of each rule that consults failableOutput, as ConstantPropagation's 
ChildColumns does (expressions.scala:768-775), pass them to failableOutput and 
splitMovable in predicates.scala, and add a case that reports through a 
non-recursive CTERelationRef the columns whose definition columns the 
definition's plan reports, as ConstantPropagation.failableColumnsOf does 
(expressions.scala:845-850); update the scaladoc and add optimizer and ANSI 
end-to-end tests with a MATERIALIZED CTE.
   
   **Why this works:** With the definition's failable columns visible through 
the reference, splitMovable keeps a condition over them in place after a 
barrier, so it never reaches the reference and the CTE rule has nothing to copy 
into the definition for it, while a condition written first still moves and is 
copied as on the base branch.
   
   **Risks:** The rule entry points that consult the helper change shape to 
carry the definitions; one that does not pass them keeps today's empty answer 
for a reference. After a non-deterministic or throwable conjunct, a condition 
over such a column also stays above the join where nothing below the 
definition's projection drops rows, as with the PR's other cases.
   
   **Constraints:** A reference takes a place in the two answers that the 
repair for conditions over both sides of a join introduces at least for 
conditions that travel below it, since a kept definition is computed in full 
before its references read it.
   
   **Exclusions:**
   - The CTE rule's own drop of non-deterministic conditions over a reference, 
which pushes the ones written after them with no join in between, is a direct 
route the PR leaves unchanged and stays outside this repair.
   
   **Verification:**
   - **Regression:** In ANSI mode, WITH c AS MATERIALIZED (SELECT CAST(l.id * 
1000000000 AS INT) AS k FROM range(10) AS l JOIN range(3) AS r ON l.id = r.id) 
SELECT * FROM c CROSS JOIN range(1) WHERE rand(10) * 10 > 100 AND k > 0 returns 
no row with whole-stage codegen on and off, where it now fails with 
CAST_OVERFLOW.
   - **Behavior:** After a non-deterministic conjunct, a condition over such a 
column of a kept CTE reference stays above the join and no filter over it 
reaches the definition, while a condition over a plain column of the reference 
is pushed and copied.
   - **Compatibility:** A condition written first over a column that a kept 
definition can fail on is still copied into the definition, and a query whose 
CTE is inlined keeps its plan.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -1306,6 +1306,37 @@ class FilterPushdownSuite extends PlanTest {
     }
   }
 
+  test("SPARK-62195: joins: do not push a condition over a column that can 
fail through a " +
+    "union, a window, a watermark, a pushdown operator or an aggregate key 
ahead of a " +
+    "non-deterministic one") {
+    // `q` can fail as the ANSI division does. These operators pass it on, the 
union from its
+    // second child by position, and so does an aggregation that groups by it, 
also as an alias.
+    // Below them, `PushPredicateThroughNonJoin` would push a condition over 
it on through the
+    // projection. So after `rand(0) > 0.1`, `q > 0` stays above the join, 
while `a > 0`, which
+    // can not fail, is pushed.
+    val relation = LocalRelation(attrA, attrB, $"t".timestamp)
+    def project(child: LogicalPlan): LogicalPlan =
+      child.select($"a", $"t", Divide($"a", $"b", 
NumericEvalContext(EvalMode.ANSI)).as("q"))
+    val projected = project(relation)
+    val winExpr = windowExpr(count($"a"), windowSpec($"q" :: Nil, Nil, 
UnspecifiedFrame))
+    val streaming = LocalRelation(Seq(attrA, attrB, $"t".timestamp), Nil, 
isStreaming = true)
+    Seq(
+      relation.select($"a", $"t", Cast($"b", 
DoubleType).as("q")).union(projected),
+      projected.window(winExpr.as("w") :: Nil, $"q" :: Nil, Nil),
+      EventTimeWatermark(UUID.randomUUID(), $"t", new CalendarInterval(0, 0, 
1000L),
+        project(streaming)),
+      projected.distribute($"q")(2),
+      projected.groupBy($"a", $"q")($"a", $"q"),

Review Comment:
   **Nit (P3):** These aggregate sides output only `a` and `q`, so nothing 
checks the boundary the new `Aggregate` case states: that a result an aggregate 
function computes over `q`, such as `max($"q").as("m")`, is not reported. If 
the check tested `a.child.references` instead of `result.references`, `m` would 
be reported and a condition over it after `rand(0) > 0.1` would stop being 
pushed, with every test in this PR still passing. Adding such a result here, 
with a condition over it that is still pushed below the join, would pin the 
boundary.
   
   **Verification:**
   - **Behavior:** With an aggregate side that also outputs the max of the 
column that can fail, a condition over that max written after rand(0) > 0.1 is 
still pushed below the join, while the condition over the grouping key stays 
above it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -274,19 +286,32 @@ trait PredicateHelper extends AliasHelper with Logging {
         case a: Attribute if below.contains(a) => a
       })
     case agg: Aggregate =>
+      val below = failableOutput(agg.child)
       AttributeSet(agg.aggregateExpressions.flatMap {
         case a: Alias =>
           val result = a.child.transform { case e: AggregateExpression => 
e.resultAttribute }
-          if (result.deterministic && 
!ExprUtils.canEvaluateUnconditionally(result)) {
+          if (result.deterministic && 
(!ExprUtils.canEvaluateUnconditionally(result) ||
+              result.references.exists(below.contains))) {
             Some(a.toAttribute)
           } else {
             None
           }
+        case a: Attribute if below.contains(a) => Some(a)
         case _ => None
       })
     case j: Join => failableOutput(j.left) ++ failableOutput(j.right)
-    case _: Filter | _: Sample | _: LocalLimit | _: GlobalLimit | _: Offset | 
_: Sort =>
+    case u: Union =>
+      val children = u.children.map(c => (c.output, failableOutput(c)))
+      AttributeSet(u.output.zipWithIndex.collect {
+        case (a, i) if children.exists { case (output, failable) =>
+          failable.contains(output(i))

Review Comment:
   **Nit (P3):** `output(i)` is evaluated before `contains` even when a child 
reports nothing, and a projection parsed from SQL has a `List` output, so each 
lookup walks `i` cells: about `k * n * n / 2` steps per call for a union of `k` 
children and `n` columns, some 2.5e7 for a `UNION ALL` of two 5,000-column 
`SELECT`s, each time a filter or barrier above forces `failableOutput`. 
Collecting each child's reported positions in one pass, for example over 
`c.output.iterator.zipWithIndex`, and skipping a child whose set is empty gives 
the same attributes in linear time.
   
   **Verification:**
   - **Behavior:** A union whose children report columns that can fail at 
different positions, with the first child reporting none, reports exactly the 
union's columns at those positions.
   - **Inspection:** The Union case of failableOutput indexes no child's output 
by position and skips a child whose reported set is empty.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -255,12 +258,21 @@ trait PredicateHelper extends AliasHelper with Logging {
    *  - [[Join]], from both sides. Only the streamed side of a broadcast hash 
join passes them
    *    through; a build side, a shuffled hash join or a sort-merge join 
computes every column, so
    *    this is conservative for them.
+   *  - [[Union]], by position: an output column is one when the column of 
some child at its
+   *    position is.
+   *  - [[Window]], [[EventTimeWatermark]] and the operators of
+   *    `PushPredicateThroughNonJoin.canPushThrough`, e.g. `Repartition` and 
`Generate`.
+   * A union outside whole-stage codegen, these other operators and an 
aggregation, for a grouping
+   * key, may compute such a column on every row they get, but 
`PushPredicateThroughNonJoin`

Review Comment:
   **Nit (P3):** `PushPredicateThroughNonJoin` has no case for a filter over a 
join; the push into a join side below the projection is 
`PushPredicateThroughJoin`'s, which `PushDownPredicates` chains with it. The 
reason given also covers only a window's partition keys, the only columns 
`PushPredicateThroughNonJoin` pushes below a `Window`, while the `Window` case 
reports every column. Those other columns count because `ColumnPruning` 
replaces a window whose outputs nothing above reads with its child, after which 
a condition over them reaches the projection. Naming `PushDownPredicates`, or 
both rules, for the path and adding the `ColumnPruning` reason would keep the 
case from being narrowed to partition keys later.
   
   **Verification:**
   - **Inspection:** failableOutput's scaladoc in predicates.scala attributes 
the push into a join side to PushPredicateThroughJoin or to PushDownPredicates, 
and states that a window's columns other than its partition keys count because 
ColumnPruning can remove a window whose outputs are unused.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -255,12 +258,21 @@ trait PredicateHelper extends AliasHelper with Logging {
    *  - [[Join]], from both sides. Only the streamed side of a broadcast hash 
join passes them
    *    through; a build side, a shuffled hash join or a sort-merge join 
computes every column, so
    *    this is conservative for them.
+   *  - [[Union]], by position: an output column is one when the column of 
some child at its
+   *    position is.
+   *  - [[Window]], [[EventTimeWatermark]] and the operators of
+   *    `PushPredicateThroughNonJoin.canPushThrough`, e.g. `Repartition` and 
`Generate`.
+   * A union outside whole-stage codegen, these other operators and an 
aggregation, for a grouping
+   * key, may compute such a column on every row they get, but 
`PushPredicateThroughNonJoin`
+   * pushes a condition over it below them, and on through the projection that 
computes it with
+   * its expression substituted, e.g. into one side of a join there, where it 
is evaluated on the
+   * rows that the join drops.

Review Comment:
   **Nit (P3):** With no join between the condition and the operator, 
`PushPredicateThroughNonJoin`'s `Window`, `Aggregate`, `Union`, 
`EventTimeWatermark` and `canPushThrough` cases still split the conjuncts 
without `failableOutput`. Reading those cases, `SELECT * FROM (SELECT k, 
count(*) OVER (PARTITION BY k) AS w FROM (SELECT CAST(l.id * 1000000000 AS INT) 
AS k FROM range(10) AS l JOIN range(3) AS r ON l.id = r.id)) WHERE rand(10) * 
10 > 100 AND k > 0` still pushes `k > 0` below the window and into `l`. The 
description leaves that to SPARK-62144 (#60766), but nothing in the code says 
so. Please add a TODO naming SPARK-62144 in this scaladoc or at those cases, 
saying also whether the watermark and `canPushThrough` cases are left to it.
   
   **Verification:**
   - **Inspection:** A TODO naming SPARK-62144 sits in failableOutput's 
scaladoc or at PushPredicateThroughNonJoin's Aggregate, Window, Union, 
EventTimeWatermark and canPushThrough cases, and says that a condition reaching 
them directly, without a join in between, still moves ahead of a 
non-deterministic or throwable one.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -274,19 +286,32 @@ trait PredicateHelper extends AliasHelper with Logging {
         case a: Attribute if below.contains(a) => a
       })
     case agg: Aggregate =>
+      val below = failableOutput(agg.child)
       AttributeSet(agg.aggregateExpressions.flatMap {
         case a: Alias =>
           val result = a.child.transform { case e: AggregateExpression => 
e.resultAttribute }
-          if (result.deterministic && 
!ExprUtils.canEvaluateUnconditionally(result)) {
+          if (result.deterministic && 
(!ExprUtils.canEvaluateUnconditionally(result) ||
+              result.references.exists(below.contains))) {
             Some(a.toAttribute)
           } else {
             None
           }
+        case a: Attribute if below.contains(a) => Some(a)
         case _ => None
       })
     case j: Join => failableOutput(j.left) ++ failableOutput(j.right)
-    case _: Filter | _: Sample | _: LocalLimit | _: GlobalLimit | _: Offset | 
_: Sort =>
+    case u: Union =>
+      val children = u.children.map(c => (c.output, failableOutput(c)))
+      AttributeSet(u.output.zipWithIndex.collect {
+        case (a, i) if children.exists { case (output, failable) =>
+          failable.contains(output(i))
+        } => a
+      })
+    case _: Filter | _: Sample | _: LocalLimit | _: GlobalLimit | _: Offset | 
_: Sort |
+         _: Window | _: EventTimeWatermark =>
       failableOutput(plan.children.head)
+    case u: UnaryNode if PushPredicateThroughNonJoin.canPushThrough(u) =>

Review Comment:
   **Non-blocking (P2):** `AsOfJoin` and `ExternalLookupJoin` are `BinaryNode`s 
rather than `Join`s, and `LateralJoin` is a `UnaryNode` that `canPushThrough` 
does not list, so all three still reach `case _ => AttributeSet.empty`, 
although conditions travel through them: `PushPredicateThroughJoin` pushes a 
filter's left-side conjuncts into a sort-merge as-of join's left input, which 
`ASOF JOIN ... MATCH_CONDITION` builds and `RewriteAsOfJoin` keeps, and 
stream-side conjuncts into a lookup join, and `RewriteLateralSubquery` turns a 
lateral join into a `Join` later in the same batch. Reading those rules, 
`SELECT * FROM (SELECT a.k, q.id AS qid FROM (SELECT CAST(l.id * 1000000000 AS 
INT) AS k, l.id AS ts FROM range(10) AS l JOIN range(3) AS r ON l.id = r.id) AS 
a ASOF JOIN range(5) AS q MATCH_CONDITION (a.ts >= q.id)) CROSS JOIN range(1) 
WHERE rand(10) * 10 > 100 AND k > 0` still moves `k > 0` past the `rand` 
conjunct and on into `l`, where the cast overflows from id 3, as in the descrip
 tion's queries. `ConstantPropagation.failableColumnsOf` already counts a 
lateral join as the join it becomes.
   
   **Recommended change:** Add cases to failableOutput in predicates.scala that 
report through an AsOfJoin and an ExternalLookupJoin the columns reported for 
both inputs, as for a Join, and through a LateralJoin those of its left side 
and of its subquery's plan, as ConstantPropagation.failableColumnsOf does 
(expressions.scala:842-843); replace the scaladoc's claim at 
predicates.scala:274-275 that no condition is pushed through the remaining 
operators with these joins; and add optimizer filter pushdown tests and an ANSI 
end-to-end test for the as-of and lateral queries.
   
   **Why this works:** With these joins reporting the columns their inputs 
report, splitMovable keeps a condition over such a column in place after a 
barrier, and the Filter case of InferFiltersFromConstraints infers no filter 
over it, so neither the as-of and lookup cases of PushPredicateThroughJoin nor 
the Join that a lateral join becomes carry it on to the projection and into a 
join below.
   
   **Risks:** After a non-deterministic or throwable conjunct, a condition over 
a column that can fail through these joins also stays above the join where 
nothing below the computing projection drops rows, so more rows reach that 
join, as with the PR's other cases; removing the cases reverts it.
   
   **Constraints:** Each new case takes a place in the two answers that the 
repair for conditions over both sides of a join introduces: an as-of join and a 
lookup join at least for conditions that travel below them, and a lateral join 
as the Join it becomes.
   
   **Exclusions:**
   - CTE references are left to their own repair, which needs the CTE 
definitions.
   
   **Verification:**
   - **Regression:** In ANSI mode, a query that reads CAST(l.id * 1000000000 AS 
INT) of a join of range(10) and range(3) through an ASOF JOIN ... 
MATCH_CONDITION, or through a LATERAL subquery, cross-joined with range(1) 
under WHERE rand(10) * 10 > 100 AND k > 0, returns no row with whole-stage 
codegen on and off, where it now fails with CAST_OVERFLOW.
   - **Behavior:** After rand(0) > 0.1, a condition over a column that an ANSI 
division computes below an as-of join, the stream side of an external lookup 
join or a lateral join stays above the join over them, while a condition over a 
plain column is pushed.
   - **Inspection:** failableOutput's scaladoc in predicates.scala lists the 
as-of, lookup and lateral joins and no longer states that no condition is 
pushed through the operators it does not look through.



-- 
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