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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteCountDistinctConditional.scala:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.spark.sql.catalyst.optimizer
+
+import org.apache.spark.sql.catalyst.expressions._
+import 
org.apache.spark.sql.catalyst.expressions.aggregate.{AggregateExpression, Count}
+import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LogicalPlan}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.AGGREGATE
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Rewrites COUNT(DISTINCT IF(cond, base, NULL)) and
+ * COUNT(DISTINCT CASE WHEN cond THEN base END) into
+ * COUNT(DISTINCT base) FILTER (WHERE cond).
+ *
+ * This canonicalization reduces the number of distinct groups seen by
+ * RewriteDistinctAggregates from N (one per unique conditional expression) 
down to 1
+ * (all share the same base column), collapsing the Expand factor from Nx to 
1x.
+ *
+ * Correctness: COUNT DISTINCT ignores NULLs, so nulling out rows where !cond
+ * is semantically identical to filtering those rows out entirely.
+ */
+object RewriteCountDistinctConditional extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (!SQLConf.get.rewriteCountDistinctConditionalEnabled) {
+      return plan
+    }
+    plan.transformUpWithPruning(_.containsPattern(AGGREGATE)) {

Review Comment:
   Consider folding this canonicalization into `RewriteDistinctAggregates` 
rather than shipping it as a separate rule that must run before it in the same 
`Once` batch.
   
   **Rule-ordering dependency.** The canonicalization is meaningful only as a 
pre-pass feeding `RewriteDistinctAggregates`'s group-by key (`ExpressionSet` of 
unfoldable children). As a standalone rule, "runs first" rests purely on batch 
position in `Optimizer.scala`, not on a structural guarantee. The natural home 
is right before the `groupBy` in `RewriteDistinctAggregates.rewrite`: normalize 
each distinct `Count(IF/CASE(cond, base, NULL))` to `Count(base)` with `filter 
= cond`, and the existing grouping collapses them onto `base`.
   
   **It also fixes a single-count pessimization for free.** Run as a separate 
pre-pass, this rule blindly converts a *lone* `COUNT(DISTINCT IF(...))` — which 
is planned today with no Expand via `planAggregateWithOneDistinct` — into a 
FILTER form that then trips `mustRewrite` and forces the Expand-based path (~2x 
row fan-out + an extra aggregation stage). Integrated into `rewrite()`, the 
normalization sits behind the `mayNeedtoRewrite` gate: a lone count (`size == 
1`, no filter) is never entered (`rewrite` returns the input unchanged), so 
there's no regression; and for >=2 distinct aggregates — where the rule was 
already going to expand — canonicalization only *reduces* the group count (Nx 
-> 1x) and can never introduce an expansion the baseline wouldn't already do.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteCountDistinctConditionalSuite.scala:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.spark.sql.catalyst.optimizer
+
+import org.apache.spark.sql.catalyst.dsl.expressions._
+import org.apache.spark.sql.catalyst.dsl.plans._
+import org.apache.spark.sql.catalyst.expressions.{Expression, If, Literal}
+import org.apache.spark.sql.catalyst.expressions.aggregate.Count
+import org.apache.spark.sql.catalyst.plans.PlanTest
+import org.apache.spark.sql.catalyst.plans.logical.LocalRelation
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.IntegerType
+
+class RewriteCountDistinctConditionalSuite extends PlanTest {
+
+  val testRelation = LocalRelation(
+    Symbol("a").int, Symbol("b").int, Symbol("c").int, Symbol("d").string)
+
+  private def countDistinctIf(cond: Expression, base: Expression): Expression 
= {
+    Count(If(cond, base, Literal(null))).toAggregateExpression(isDistinct = 
true)
+  }
+
+  private def countDistinctCaseWhen(cond: Expression, base: Expression): 
Expression = {
+    val caseWhen = org.apache.spark.sql.catalyst.expressions.CaseWhen(
+      Seq((cond, base)),
+      None)
+    Count(caseWhen).toAggregateExpression(isDistinct = true)
+  }
+
+  private def countDistinctCaseWhenElseNull(cond: Expression, base: 
Expression): Expression = {
+    val caseWhen = org.apache.spark.sql.catalyst.expressions.CaseWhen(
+      Seq((cond, base)),
+      Some(Literal(null)))
+    Count(caseWhen).toAggregateExpression(isDistinct = true)
+  }
+
+  test("disabled by default") {
+    val input = testRelation
+      .groupBy(Symbol("a"))(
+        countDistinctIf(Symbol("b") > 1, Symbol("c")).as("cnt1"))
+      .analyze
+
+    val optimized = RewriteCountDistinctConditional(input)
+    comparePlans(optimized, input)
+  }
+
+  test("rewrite COUNT(DISTINCT IF(cond, col, NULL)) to COUNT(DISTINCT col) 
FILTER") {
+    val input = testRelation
+      .groupBy(Symbol("a"))(
+        countDistinctIf(Symbol("b") > 1, Symbol("c")).as("cnt1"))
+      .analyze
+
+    withSQLConf(SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> 
"true") {
+      val optimized = RewriteCountDistinctConditional(input)
+
+      val expected = testRelation
+        .groupBy(Symbol("a"))(
+          countDistinctWithFilter(Symbol("b") > 1, Symbol("c")).as("cnt1"))
+        .analyze
+
+      comparePlans(optimized, expected)
+    }
+  }
+
+  test("rewrite COUNT(DISTINCT CASE WHEN cond THEN col END) to COUNT(DISTINCT 
col) FILTER") {
+    val input = testRelation
+      .groupBy(Symbol("a"))(
+        countDistinctCaseWhen(Symbol("b") > 1, Symbol("c")).as("cnt1"))
+      .analyze
+
+    withSQLConf(SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> 
"true") {
+      val optimized = RewriteCountDistinctConditional(input)
+
+      val expected = testRelation
+        .groupBy(Symbol("a"))(
+          countDistinctWithFilter(Symbol("b") > 1, Symbol("c")).as("cnt1"))
+        .analyze
+
+      comparePlans(optimized, expected)
+    }
+  }
+
+  test("rewrite COUNT(DISTINCT CASE WHEN cond THEN col ELSE NULL END)") {
+    val input = testRelation
+      .groupBy(Symbol("a"))(
+        countDistinctCaseWhenElseNull(Symbol("b") > 1, Symbol("c")).as("cnt1"))
+      .analyze
+
+    withSQLConf(SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> 
"true") {
+      val optimized = RewriteCountDistinctConditional(input)
+
+      val expected = testRelation
+        .groupBy(Symbol("a"))(
+          countDistinctWithFilter(Symbol("b") > 1, Symbol("c")).as("cnt1"))
+        .analyze
+
+      comparePlans(optimized, expected)
+    }
+  }
+
+  test("multiple conditional distinct counts collapse to single distinct 
group") {
+    val input = testRelation
+      .groupBy(Symbol("a"))(
+        countDistinctIf(Symbol("b") > 1, Symbol("c")).as("cnt1"),
+        countDistinctIf(Symbol("b") > 2, Symbol("c")).as("cnt2"),
+        countDistinctIf(Symbol("b") > 3, Symbol("c")).as("cnt3"))
+      .analyze
+
+    withSQLConf(SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> 
"true") {
+      val optimized = RewriteCountDistinctConditional(input)
+
+      val expected = testRelation
+        .groupBy(Symbol("a"))(
+          countDistinctWithFilter(Symbol("b") > 1, Symbol("c")).as("cnt1"),
+          countDistinctWithFilter(Symbol("b") > 2, Symbol("c")).as("cnt2"),
+          countDistinctWithFilter(Symbol("b") > 3, Symbol("c")).as("cnt3"))
+        .analyze
+
+      comparePlans(optimized, expected)
+
+      // Verify RewriteDistinctAggregates sees only 1 distinct group
+      val rewritten = RewriteDistinctAggregates(optimized)
+      // Should be rewritten (not same as input) because there are now multiple
+      // distinct expressions with the same base column
+      assert(rewritten != optimized)

Review Comment:
   This assertion only checks that *some* rewrite happened — it's true whether 
`RewriteDistinctAggregates` collapses the three counts into one distinct group 
or leaves them as three. It doesn't actually verify the "sees only 1 distinct 
group" collapse that the comment claims and that this PR exists to achieve. 
Consider asserting the resulting distinct-group / `Expand` projection count is 
1 (e.g. count `Expand` output projections, or assert all three counts share a 
single group) so the test guards the collapse rather than just "changed".



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