cloud-fan commented on code in PR #60403:
URL: https://github.com/apache/spark/pull/60403#discussion_r4562643198


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2315,6 +2315,24 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
 
         case _ => join
       }
+
+    // A right row that fails the ON condition is never the match of any left 
row, so a filter
+    // that follows from the left constraints and the ON condition can drop it 
before the join.
+    // An inner join also drops the left rows without a match, so its left 
side gets one too.
+    case j: AsOfJoin =>
+      // Leave out IN and correlated EXISTS filters. They become joins below 
the as-of join. A
+      // sort-merge semi join keeps only the key order, so the as-of join 
sorts that input again.
+      // A NOT IN anti join runs over every row of that input, and it is a 
nested-loop join when
+      // spark.sql.optimizeNullAwareAntiJoin is off.
+      val allConstraints = getAllConstraints(j.left, j.right, j.condition)
+        .filterNot(SubqueryExpression.hasInOrCorrelatedExistsSubquery)

Review Comment:
   **Non-blocking (P2):** This drops subquery predicates from the as-of case's 
own constraint set, but `inferFilters` is a top-down transform that then visits 
the children of the node this case returns (TreeNode.scala:594-597). So the 
`Filter` case at Optimizer.scala:2285-2292 runs on each new `Filter`. Its 
constraints include the input's own uncorrelated IN or NOT IN predicate, since 
`Filter.validConstraints` drops only correlated subqueries, next to the 
equality or literal this case just added. Transitivity or literal binding 
rewrites the subquery predicate, `canBeFilter` accepts it, and 
`RewritePredicateSubquery` later turns it into another semi or anti join below 
the as-of join.
   
   Two examples, from reading the code:
   - `l LEFT ASOF JOIN (SELECT * FROM r WHERE r.a NOT IN (SELECT x FROM s)) r 
MATCH_CONDITION (l.ts >= r.ts) ON l.k = r.k AND l.k = r.a`: this case adds `r.k 
= r.a` to the right input, and the `Filter` case then adds `r.k NOT IN (SELECT 
x FROM s)`, so the right input gets two null-aware anti joins.
   - `trades t LEFT ASOF JOIN (SELECT * FROM quotes WHERE (symbol, venue) IN 
(SELECT symbol, venue FROM listed)) q MATCH_CONDITION (t.ts >= q.ts) ON 
t.symbol = q.symbol WHERE t.symbol = 'MSFT'`: this case adds `q.symbol = 
'MSFT'`, and the `Filter` case adds `('MSFT', q.venue) IN (SELECT symbol, venue 
FROM listed)`, a second semi join.
   
   Results stay the same, but that input runs its subquery join twice over the 
rows the inferred filter keeps: two broadcast hash anti joins for a 
single-column NOT IN, or a second sort-merge semi join with its own shuffle and 
sort for an IN too large to broadcast. Whether the whole plan does more work 
than on the base branch depends on how many rows the inferred filter removes. 
No test covers an input that already has a subquery predicate next to an 
inferred equality or literal binding.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60403#discussion_r4559803534).
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2315,6 +2315,24 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
 
         case _ => join
       }
+
+    // A right row that fails the ON condition is never the match of any left 
row, so a filter
+    // that follows from the left constraints and the ON condition can drop it 
before the join.
+    // An inner join also drops the left rows without a match, so its left 
side gets one too.
+    case j: AsOfJoin =>
+      // Leave out IN and correlated EXISTS filters. They become joins below 
the as-of join. A
+      // sort-merge semi join keeps only the key order, so the as-of join 
sorts that input again.
+      // A NOT IN anti join runs over every row of that input, and it is a 
nested-loop join when
+      // spark.sql.optimizeNullAwareAntiJoin is off.
+      val allConstraints = getAllConstraints(j.left, j.right, j.condition)

Review Comment:
   **Blocking (P1):** These constraints reach the inputs through 
`inferNewFilter`, whose `canBeFilter` returns true for every constraint when 
`spark.sql.legacy.inferFailableFiltersFromConstraints` is on 
(Optimizer.scala:2371-2374). Under that flag the as-of case adds filters that 
can fail or are otherwise observable to the right input of both join types and 
to the left input of an inner join.
   
   Take the query of the PR's own test 'a right filter inferred from the ON 
condition is not added if it can fail', with ANSI mode on and the flag set. 
`WHERE t.lo = 0` is pushed into the left input, literal binding turns `CAST(r.v 
AS INT) >= t.lo` into `CAST(r.v AS INT) >= 0`, and that filter lands on the 
right input, where it casts `'abc'`. From reading the code, the query then 
fails with `CAST_INVALID_INPUT`, as the test's own comment says it would, while 
the base branch returns `(1, '42')` and `(2, NULL)` with the same settings.
   
   The flag is how users restore the previous inference 
(docs/sql-migration-guide.md:86), and for as-of joins the previous behavior, on 
the base branch and in 4.3.0, is no inferred filter at all. The as-of pushdown 
in `PushPredicateThroughJoin` also never moves a throwable predicate below the 
as-of join (Optimizer.scala:3214-3223). No test runs the as-of inference with 
the flag on.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2315,6 +2315,24 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
 
         case _ => join
       }
+
+    // A right row that fails the ON condition is never the match of any left 
row, so a filter
+    // that follows from the left constraints and the ON condition can drop it 
before the join.
+    // An inner join also drops the left rows without a match, so its left 
side gets one too.
+    case j: AsOfJoin =>
+      // Leave out IN and correlated EXISTS filters. They become joins below 
the as-of join. A
+      // sort-merge semi join keeps only the key order, so the as-of join 
sorts that input again.
+      // A NOT IN anti join runs over every row of that input, and it is a 
nested-loop join when
+      // spark.sql.optimizeNullAwareAntiJoin is off.
+      val allConstraints = getAllConstraints(j.left, j.right, j.condition)
+        .filterNot(SubqueryExpression.hasInOrCorrelatedExistsSubquery)
+      val newLeft = j.joinType match {
+        case Inner => inferNewFilter(j.left, allConstraints)
+        case LeftOuter => j.left
+        case other =>
+          throw SparkException.internalError(s"Unexpected as-of join type: 
$other")
+      }
+      j.copy(left = newLeft, right = inferNewFilter(j.right, allConstraints))

Review Comment:
   **Non-blocking (P2):** For a LEFT ASOF JOIN this filters only the right 
input, with at least `IS NOT NULL` on each nullable `=` ON key, and leaves the 
left input as is. When both inputs read the same relation, the base branch 
plans them as identical `Exchange(hashpartitioning(key), Scan)` subtrees, and 
exchange reuse shares one of them. With this change the right scan carries the 
pushed `isnotnull` in its data filters, which 
`FileSourceScanExec.doCanonicalize` includes 
(DataSourceScanExec.scala:1021-1038), so the two exchanges no longer match.
   
   For example, take `SELECT a.id, a.ts, a.v, b.ts, b.v FROM events a LEFT ASOF 
JOIN events b MATCH_CONDITION (a.ts > b.ts) ON a.id = b.id` over a parquet 
table whose `id` is nullable. From reading the planner code, the base branch 
scans `events` once and reuses its shuffle, while this change scans and 
shuffle-writes it twice. That extra work grows with the table size, and the 
filter saves only the work on NULL-key right rows. Several as-of joins against 
the same right relation with different inferred filters, such as UNION ALL 
branches with different left key filters, lose their shared right exchange the 
same way. An inner as-of self join keeps its reuse, because both inputs get the 
same filter.
   
   The rule's regular left outer join case makes the same trade-off for regular 
left outer self joins, so keeping the filter is a reasonable choice. But the PR 
description reports only a two-table measurement and does not state this cost, 
the alternative of leaving the right input unfiltered when both inputs are the 
same plan, or why the change keeps the filter.
   
   **Verification:**
   - **Inspection:** The comment and the PR description name the lost exchange 
reuse for a LEFT ASOF JOIN of a relation with itself, the alternative of 
leaving the right input unfiltered when both inputs are the same plan, and the 
reason the change keeps the right-side filter.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2315,6 +2315,24 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
 
         case _ => join
       }
+
+    // A right row that fails the ON condition is never the match of any left 
row, so a filter
+    // that follows from the left constraints and the ON condition can drop it 
before the join.
+    // An inner join also drops the left rows without a match, so its left 
side gets one too.
+    case j: AsOfJoin =>
+      // Leave out IN and correlated EXISTS filters. They become joins below 
the as-of join. A
+      // sort-merge semi join keeps only the key order, so the as-of join 
sorts that input again.
+      // A NOT IN anti join runs over every row of that input, and it is a 
nested-loop join when
+      // spark.sql.optimizeNullAwareAntiJoin is off.

Review Comment:
   **Nit (P3):** `RewritePredicateSubquery` builds one `a = x OR isnull(a = x)` 
conjunct per NOT IN column, and `ExtractSingleColumnNullAwareAntiJoin` matches 
only a single such conjunct (patterns.scala:407-412). So a NOT IN over more 
than one nullable column has no equi-join keys and is planned as a broadcast 
nested-loop join with `spark.sql.optimizeNullAwareAntiJoin` at its default of 
true. An example is `(q.k, 'X') NOT IN (SELECT x, y FROM s)`, which this case 
can infer from a left `(t.k, t.c) NOT IN (SELECT x, y FROM s)` with `t.c = 'X'` 
and `ON t.k = q.k`. The comment is right for a single-column NOT IN, which gets 
the null-aware broadcast hash anti join by default whatever its subquery size, 
because `spark.sql.optimizeNullAwareAntiJoin.broadcastThreshold` defaults to -1 
(joins.scala:521-532). The PR description repeats the sentence.
   
   ```suggestion
         // A NOT IN anti join runs over every row of that input. Over nullable 
columns, it is a
         // nested-loop join if it has several columns or 
spark.sql.optimizeNullAwareAntiJoin is off.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60403#discussion_r4559803534).
   
   **Verification:**
   - **Inspection:** The comment's condition for a nested-loop NOT IN anti join 
matches how the planner chooses the null-aware broadcast hash anti join: only 
for a single-column NOT IN with spark.sql.optimizeNullAwareAntiJoin on, which 
the default spark.sql.optimizeNullAwareAntiJoin.broadcastThreshold of -1 admits 
whatever the size of its subquery result.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2315,6 +2315,19 @@ object InferFiltersFromConstraints extends 
Rule[LogicalPlan]
 
         case _ => join
       }
+
+    // A right row that fails the ON condition is never the match of any left 
row, so a filter
+    // that follows from the left constraints and the ON condition can drop it 
before the join.
+    // An inner join also drops the left rows without a match, so its left 
side gets one too.
+    case j: AsOfJoin =>
+      val allConstraints = getAllConstraints(j.left, j.right, j.condition)
+      val newLeft = j.joinType match {
+        case Inner => inferNewFilter(j.left, allConstraints)
+        case LeftOuter => j.left
+        case other =>
+          throw SparkException.internalError(s"Unexpected as-of join type: 
$other")
+      }
+      j.copy(left = newLeft, right = inferNewFilter(j.right, allConstraints))

Review Comment:
   Thanks for the fix and for checking the plans. You're right about NOT IN, 
and my comment was wrong there: 
spark.sql.optimizeNullAwareAntiJoin.broadcastThreshold defaults to -1, so a 
single-column NOT IN is planned as a null-aware broadcast hash anti join 
whatever the size of its subquery result (getBroadcastHashJoinBuildSide in 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:521-532).
 A NOT IN over more than one nullable column is still a broadcast nested-loop 
join with the default settings, because only the single-column shape can use 
the hash join. This review raises two related points: the new code comment 
leaves out that multi-column case, and an inferred IN or NOT IN filter can 
still reach an as-of input that already has a subquery filter of its own.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4559803534","thread_id":"inline:4559803534","verdict_sha256":"53d489b9e4f9ddcdd73bed04065692b177a2d90ed878d659e1ccf8c4c7c8b21e"}
 -->



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