hhr293 commented on code in PR #12756: URL: https://github.com/apache/gluten/pull/12756#discussion_r3823018347
########## backends-velox/src/main/scala/org/apache/gluten/extension/RewriteSelfJoinInequalityToAggregate.scala: ########## @@ -0,0 +1,722 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.gluten.extension + +import org.apache.gluten.config.VeloxConfig + +import org.apache.spark.internal.Logging +import org.apache.spark.sql.SparkSession +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.RowOrdering +import org.apache.spark.sql.catalyst.expressions.aggregate._ +import org.apache.spark.sql.catalyst.plans._ +import org.apache.spark.sql.catalyst.plans.logical._ +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.types.LongType + +/** + * Rewrites self-join with inequality into GROUP BY + HAVING COUNT(DISTINCT) > 1. + * + * Targets three patterns; all require an existence-only context (LeftSemi/LeftAnti join, or + * InSubquery/Exists expression) so that row-count multiplicity from the self-join cross-product + * does not affect semantics. + * + * - Pattern A' (InSubquery/Exists primary): InSubquery/Exists whose subquery top-level join is a + * direct self-join. The primary path for TPC-DS Q95. + * - Pattern A2 (nested): InSubquery/Exists whose subquery contains an outer InnerJoin that has a + * self-join child. Only the self-join child is replaced with Aggregate; the outer join is + * preserved. + * - Pattern A (LeftSemi/LeftAnti): LeftSemi/LeftAnti whose right child is an Inner self-join + * (possibly wrapped in Project). Matches semi/anti joins that already exist in the input -- + * e.g. from an explicit `LEFT SEMI JOIN` clause. Note: this rule is injected via + * `injectOptimizerRule`, which places it in the operator-optimization batch that runs BEFORE + * `RewritePredicateSubquery`; A is NOT a post-subquery-rewrite fallback for A'. + * + * Correlated subqueries (outer references / joinCond in ListQuery/Exists) are fail-closed at the + * entry expression, since our ExprId canonicalization does not remap those predicates. + * + * All three share: + * - [[buildAggregateHavingDistinctGt1]] to construct `Filter(cnt > 1, Aggregate)` + * - [[canonicalizeWrapper]] to rebuild a wrapping Project so every equi-key reference points to + * the sjLeft-side attribute, with **fresh exprIds** (Spark's SPARK-21835 style -- no reuse of + * original exprIds), returning an old->new attribute remap for downstream rewrite. + * + * Controlled by `spark.gluten.sql.rewrite.selfJoinInequality` (default false, opt-in). + */ +case class RewriteSelfJoinInequalityToAggregate(spark: SparkSession) + extends Rule[LogicalPlan] + with PredicateHelper + with Logging { + + private val CountDistinctAliasName = "_gluten_rw_selfjoin_cnt_distinct" + + override def apply(plan: LogicalPlan): LogicalPlan = { + if (!VeloxConfig.get.enableRewriteSelfJoinInequality) { + logDebug("RewriteSelfJoinInequalityToAggregate: disabled via config, skipping") + return plan + } + + // Pattern A: rewrite LeftSemi/LeftAnti whose right child is an Inner self-join. + val afterOps = plan.transformUp { + case j: Join + if (j.joinType == LeftSemi || j.joinType == LeftAnti) && + j.condition.isDefined && + isInnerJoinShape(j.right) => + tryRewriteSemiWithSelfJoinChild(j).getOrElse(j) + case other => other + } + + // Pattern A' / A2: rewrite subquery plans embedded in InSubquery/Exists. + // Type-based matching (`x: T`) + named-argument copy keeps this portable across + // Spark 3.3/3.4/3.5/4.x where ListQuery/Exists case-class arity has drifted. + // + // Correlated subquery fail-closed: `SubqueryExpression.children.nonEmpty` iff the + // subquery has outer references / correlated join conditions. These predicates + // reference attributes INSIDE the subquery plan by ExprId; our canonicalizeWrapper + // rewrites those ExprIds without remapping the correlated predicates, which would + // leave dangling references after `RewritePredicateSubquery` folds them back into + // the semi-join condition. Target workload (TPC-DS Q95) is uncorrelated, so bail + // on any correlated candidate rather than growing the remap surface. + val rewritten = afterOps.transformAllExpressions { + case in @ InSubquery(_, lq: ListQuery) if lq.children.isEmpty => + rewriteSubqueryPlan(lq.plan) match { + case Some(newSub) => in.copy(query = lq.copy(plan = newSub)) + case None => in + } + case ex: Exists if ex.children.isEmpty => Review Comment: Thanks for digging into the optimizer ordering in detail. I agree with your analysis. Given that uncorrelated `Exists` has already been rewritten by `RewriteNonCorrelatedExists` before this injected rule runs, while correlated `Exists` is intentionally filtered by the `children.isEmpty` guard, the current `Exists` branch does not provide effective coverage here. For this PR, I'll remove the unreachable `Exists` branch and update the config description, class comment, and documentation accordingly. I'll leave real `EXISTS` support to a follow-up, where it can be redesigned around the actual post-`RewriteNonCorrelatedExists` `ScalarSubquery(Limit 1, ...)` shape with dedicated tests. -- 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]
