You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by we...@apache.org on 2026/10/21 18:29:42 UTC
(spark) branch branch-4.x updated: [SPARK-56898][SQL] Rewrite COUNT(DISTINCT IF) to COUNT(DISTINCT) FILTER with a union-of-filters guard
This is an automated email from the ASF dual-hosted git repository.
cloud-fan pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/branch-4.x by this push:
new 500af2acecdc [SPARK-56898][SQL] Rewrite COUNT(DISTINCT IF) to COUNT(DISTINCT) FILTER with a union-of-filters guard
500af2acecdc is described below
commit 500af2acecdccfc91ce8813a01ec64aaa370d3c8
Author: James Xu <xu...@gmail.com>
AuthorDate: Wed Oct 21 18:29:02 2026 +0000
[SPARK-56898][SQL] Rewrite COUNT(DISTINCT IF) to COUNT(DISTINCT) FILTER with a union-of-filters guard
### What changes were proposed in this pull request?
`RewriteDistinctAggregates` canonicalizes conditional distinct counts into
FILTER form:
```sql
COUNT(DISTINCT IF(cond, base, NULL)) -> COUNT(DISTINCT base) FILTER (WHERE cond)
COUNT(DISTINCT CASE WHEN cond THEN base END) -> COUNT(DISTINCT base) FILTER (WHERE cond)
```
so that multiple conditional counts over the same base column collapse from N
distinct groups into one, reducing the Expand fan-out from N x to 1 x. The
union of the member filters then guards the group's shared distinct key
(filters deduplicated by canonicalized form):
```sql
SELECT key,
COUNT(DISTINCT IF(cond1, base, NULL)),
COUNT(DISTINCT IF(cond2, base, NULL))
-- is collapsed into one distinct group whose Expand key is
IF(Or(cond1, cond2), base, NULL)
```
Rows matching no filter project NULL as the key and merge into a single NULL
key per group value, keeping the first (map-side partial) aggregate's output
cardinality bounded by the pre-rewrite plan:
```
distinct(base | Or(conds)) + 1 <= sum_i distinct(base | cond_i) + N
```
The guard applies only when it is safe and never harmful:
- every aggregate in the group is filtered — an unfiltered one needs the raw
base over all rows;
- all filters are deterministic — the guard evaluates each condition a second
time, beside its flag column;
- no filter contains a predicate subquery — IN, EXISTS, and NOT IN are still
subquery expressions when this rule runs, and copying one into the Expand
key would build a second ExistenceJoin; for the same reason, a conditional
count whose condition contains a subquery is not normalized;
- the base expression must be safe to evaluate unconditionally (plain columns,
comparisons, Coalesce, struct/map accessors; expressions that can throw,
e.g. Cast under ANSI mode, are excluded), since the guard evaluates the base
on rows matched by *any* member filter.
A single filtered distinct count (user-written `FILTER` syntax) gets the guard
as well, bounding its key cardinality the same way. Both the IF/CASE rewrite and
the union-of-filters guard are gated by the internal config
`spark.sql.optimizer.rewriteCountDistinctConditional.enabled` (default true).
`rewrite()` only keeps the normalized form when it strictly reduces the number
of distinct groups. Separately, a conditional COUNT whose IF/CASE child is also
the distinct child of an aggregate that is not normalized, for example
`SUM(DISTINCT IF(...))` on the same expression, stays in that shared group even
when other conditional counts on the same base do collapse. Collapsing the
shared count would carry that child's keys in both the guarded `{base}` group
and the surviving shared group.
When `spark.sql.optimizer.optimizeExpandRatio` is also enabled, the normalized
FILTER form is currently ineligible for `OptimizeExpand` pre-aggregation
because the Expand carries filter flags. On duplicate-heavy inputs, enabling
both can therefore trade lower Expand fan-out for losing pre-aggregation;
SPARK-60318 tracks allowing the duplicate-insensitive `max(flag)` columns.
### Why are the changes needed?
N conditional counts over the same column otherwise create N distinct groups,
and the Expand amplifies every input row N times into the partial aggregates.
Collapsing them into one group removes the amplification, and the
union-of-filters guard ensures the collapsed plan is never worse than the
uncollapsed one, regardless of predicate selectivity.
Benchmark (ExpandBenchmark, local), covering both predicate regimes:
- overlapping day windows (9 conditional COUNT(DISTINCT) + 9 conditional SUM,
nested windows covering all rows, 5M rows):
conf off (9 distinct groups): 50,561 ms/op
conf on (1 collapsed group): 10,118 ms/op (5.0x faster)
- disjoint ~1%-selective predicates (10 conditional COUNT(DISTINCT) over a
unique base column, 10M rows):
conf off (10 distinct groups): 15,670 ms/op
conf on (1 guarded group): 1,531 ms/op (10.2x faster)
### Does this PR introduce _any_ user-facing change?
Yes, for the default (`spark.sql.optimizer.rewriteCountDistinctConditional.enabled=true`).
In addition to conditional `COUNT(DISTINCT IF/CASE)` queries, the union-of-filters
guard also applies to existing user-written `COUNT(DISTINCT ...) FILTER (WHERE ...)`
aggregates that go through Expand. For a distinct child that is safe to evaluate
unconditionally, the Expand key becomes `IF(Or(filters), child, NULL)`, so that
argument is no longer evaluated on rows that match no filter. A child that can
throw, such as a division, keeps the raw Expand key. Under ANSI,
`COUNT(DISTINCT 10 / x) FILTER (WHERE x <> 0)` still raises `DIVIDE_BY_ZERO` on
`x = 0`, as it did before this PR. `EXPLAIN` plans for guarded shapes change
accordingly. Ordinary non-throwing queries keep the same answers.
Setting the config to `false` disables both the IF/CASE rewrite and the guard,
restoring the pre-PR Expand key and evaluation domain.
### How was this patch tested?
- `RewriteDistinctAggregatesSuite`: guard-shape assertions (Expand key is
`IF(Or(conds), base, NULL)` with the Or leaves set-equal to the member
filters) plus negative controls — an unfiltered member keeps the raw key, a
throwable child such as a division keeps the raw key, and a
nondeterministic filter disables the guard.
- `RewriteDistinctAggregatesConditionalQuerySuite` (conf on and off):
high-cardinality base with selective disjoint predicates; overlapping
windows mixed with disjoint flags; nullable conditions that are NULL for
some rows (with guarded Expand key assertion); mixed filtered/unfiltered
counts.
- Follow-ups from review: keep normalize only when distinct groups drop;
gate the union guard on the same config; tighten plan-test helpers.
- `conditional: IF shared with an un-normalizable distinct agg is not
normalized`: the COUNT that shares its IF with `SUM(DISTINCT IF(...))`
stays on that raw IF key, and the other two conditional counts collapse
under a guard covering exactly those two conditions.
- Conf-on and conf-off ExistenceJoin counts: `EXISTS`, `IN`, and `NOT IN`
filters, and IF/CASE conditions containing those predicates, both keep 3
existence joins. The IF/CASE forms are not rewritten to FILTER.
- The SPARK-58501 codegen test comment was updated to record why this query
is unchanged: the bases differ (`k` vs `v`), so the conditional rewrite does
not apply, each branch keeps its original IF, and `sinh(v)` is evaluated
once per branch (once per input row with subexpression elimination).
- `ExpandBenchmark` gained two workload sections, one per predicate regime:
overlapping day windows (covering all rows) and disjoint ~1%-selective
predicates over a unique base column, each comparing the conf off and on
plans; the benchmark will be run via the GitHub Actions benchmark workflow
for a consistent environment.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Pi
Closes #59402 from xumingming/reland-count-distinct-filter.
Authored-by: James Xu <xu...@gmail.com>
Signed-off-by: Wenchen Fan <we...@databricks.com>
(cherry picked from commit 7e5fb20923f66bb1a1365d6d18d7e971c45f7ca6)
Signed-off-by: Wenchen Fan <we...@databricks.com>
---
.../optimizer/RewriteDistinctAggregates.scala | 206 +++++-
.../org/apache/spark/sql/internal/SQLConf.scala | 32 +
.../optimizer/RewriteDistinctAggregatesSuite.scala | 716 ++++++++++++++++++++-
...teDistinctAggregatesConditionalQuerySuite.scala | 533 +++++++++++++++
.../sql/execution/WholeStageCodegenSuite.scala | 10 +-
.../sql/execution/benchmark/ExpandBenchmark.scala | 117 +++-
6 files changed, 1576 insertions(+), 38 deletions(-)
diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala
index 5aef82b64ed3..edb38ad1e3ba 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala
@@ -21,7 +21,8 @@ import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.expressions.aggregate._
import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, Expand, LogicalPlan}
import org.apache.spark.sql.catalyst.rules.Rule
-import org.apache.spark.sql.catalyst.trees.TreePattern.AGGREGATE
+import org.apache.spark.sql.catalyst.trees.TreePattern.{AGGREGATE, CASE_WHEN, IF, PLAN_EXPRESSION}
+import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.IntegerType
import org.apache.spark.util.collection.Utils
@@ -157,8 +158,8 @@ import org.apache.spark.util.collection.Utils
* output = ['key, 'cat1, 'cat2, 'gid, 'max_cond1, 'max_cond2, 'total])
* Expand(
* projections = [('key, null, null, 0, null, null, cast('value as bigint), 'id),
- * ('key, 'cat1, null, 1, 'id > 1, null, null, null),
- * ('key, null, 'cat2, 2, null, 'id > 2, null, null)]
+ * ('key, if('id > 1, 'cat1, null), null, 1, 'id > 1, null, null, null),
+ * ('key, null, if('id > 2, 'cat2, null), 2, null, 'id > 2, null, null)]
* output = ['key, 'cat1, 'cat2, 'gid, 'cond1, 'cond2, 'value, 'id])
* LocalTableScan [...]
* }}}
@@ -173,7 +174,13 @@ import org.apache.spark.util.collection.Utils
* later on. Groups can by identified by a group id (gid) column added by the expand operator.
* If distinct group exists filter clause, the expand will calculate the filter and output it's
* result (e.g. cond1) which will be used to calculate the global conditions (e.g. max_cond1)
- * equivalent to filter clauses.
+ * equivalent to filter clauses. When rewriteCountDistinctConditional is enabled, the distinct
+ * key of a group whose aggregates are all filtered, whose filters are deterministic and
+ * subquery-free, and whose children are safe to evaluate unconditionally, is guarded by the
+ * union of their filters (e.g. if('id > 1, 'cat1, null)):
+ * rows matching no predicate project NULL as the key and collapse into a single key of the
+ * first aggregate, keeping its output cardinality bounded by the un-rewritten plan. A
+ * child that is not safe to evaluate unconditionally stays the raw key.
* 2. De-duplicate the distinct paths and aggregate the non-aggregate path. The group by clause of
* this aggregate consists of the original group by clause, all the requested distinct columns
* and the group id. Both de-duplication of distinct column and the aggregation of the
@@ -223,27 +230,47 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan] {
case a: Aggregate if mayNeedtoRewrite(a) => rewrite(a)
}
- def rewrite(a: Aggregate): Aggregate = {
+ /**
+ * Groups distinct aggregate expressions by their unfoldable children. Aggregates that
+ * share a key can share one Expand projection (or the single-distinct physical path).
+ */
+ private def groupDistinctAggs(
+ aggExpressions: Seq[AggregateExpression]): Map[ExpressionSet, Seq[AggregateExpression]] = {
+ aggExpressions.filter(_.isDistinct).groupBy { e =>
+ val unfoldableChildren = ExpressionSet(e.aggregateFunction.children.filter(!_.foldable))
+ if (unfoldableChildren.nonEmpty) {
+ // Only expand the unfoldable children
+ unfoldableChildren
+ } else {
+ // If aggregateFunction's children are all foldable
+ // we must expand at least one of the children (here we take the first child),
+ // or If we don't, we will get the wrong result, for example:
+ // count(distinct 1) will be explained to count(1) after the rewrite function.
+ // Generally, the distinct aggregateFunction should not run
+ // foldable TypeCheck for the first child.
+ ExpressionSet(e.aggregateFunction.children.take(1))
+ }
+ }
+ }
+ private def numDistinctAggGroups(a: Aggregate): Int =
+ groupDistinctAggs(collectAggregateExprs(a)).size
+
+ def rewrite(origAgg: Aggregate): Aggregate = {
+ // Keep the normalized form only when it strictly reduces the number of distinct
+ // groups. Otherwise shapes like COUNT(DISTINCT IF) + SUM(DISTINCT IF) (same IF)
+ // or a repeated COUNT(DISTINCT IF) next to COUNT(*) would move from the
+ // single-distinct path onto an Expand with no fan-out win.
+ val normalized = normalizeCountDistinctConditional(origAgg)
+ val a =
+ if (numDistinctAggGroups(normalized) < numDistinctAggGroups(origAgg)) {
+ normalized
+ } else {
+ origAgg
+ }
val aggExpressions = collectAggregateExprs(a)
val distinctAggs = aggExpressions.filter(_.isDistinct)
-
- // Extract distinct aggregate expressions.
- val distinctAggGroups = aggExpressions.filter(_.isDistinct).groupBy { e =>
- val unfoldableChildren = ExpressionSet(e.aggregateFunction.children.filter(!_.foldable))
- if (unfoldableChildren.nonEmpty) {
- // Only expand the unfoldable children
- unfoldableChildren
- } else {
- // If aggregateFunction's children are all foldable
- // we must expand at least one of the children (here we take the first child),
- // or If we don't, we will get the wrong result, for example:
- // count(distinct 1) will be explained to count(1) after the rewrite function.
- // Generally, the distinct aggregateFunction should not run
- // foldable TypeCheck for the first child.
- ExpressionSet(e.aggregateFunction.children.take(1))
- }
- }
+ val distinctAggGroups = groupDistinctAggs(aggExpressions)
// Aggregation strategy can handle queries with a single distinct group without filter clause.
if (distinctAggGroups.size > 1 || mustRewrite(distinctAggs, a.groupingExpressions)) {
@@ -290,9 +317,44 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan] {
case e => nullify(e)
}
+ // Union-of-filters guard for the shared distinct key. Without the guard, the
+ // Expand projects the raw child for every row, so every distinct child value
+ // becomes a key of the first aggregate, no matter how few rows the filters
+ // select. Guarding the key with the union of the filters restores the
+ // NULL-collapse: rows matching no predicate project NULL as the key and merge
+ // into one key, keeping the first aggregate's output bounded by the
+ // pre-rewrite plan:
+ // distinct(child | Or(filters)) + 1 <= sum_i distinct(child | filter_i) + n
+ // The guard must not apply when the group contains an unfiltered aggregate
+ // (it needs the raw child over all rows). The guard re-evaluates each
+ // filter, so every filter must be deterministic and free of subqueries.
+ // IN, EXISTS, and NOT IN are still subquery expressions here:
+ // RewritePredicateSubquery runs later and builds one ExistenceJoin per
+ // occurrence, with no dedup, so copying the filter into the key would
+ // join the input twice. The guard also evaluates the child only when the
+ // union is true, so every child must pass canEvaluateUnconditionally. A
+ // child that fails, such as a division, stays raw and keeps today's
+ // evaluation count and error behavior. The guard shares the
+ // rewriteCountDistinctConditional kill switch so conf=false restores the
+ // pre-feature Expand key (raw child) for user-written FILTER distincts too.
+ val canGuard = SQLConf.get.rewriteCountDistinctConditionalEnabled &&
+ expressions.forall(_.filter.isDefined) &&
+ filters.forall { f =>
+ f.deterministic && !f.containsPattern(PLAN_EXPRESSION)
+ } &&
+ group.forall(ExprUtils.canEvaluateUnconditionally)
+ val guardCondOpt = if (canGuard) {
+ Some(filters.distinctBy(_.canonicalized).reduce(Or))
+ } else {
+ None
+ }
+
// Expand projection
val projection = distinctAggChildren.map {
- case e if group.contains(e) => e
+ case e if group.contains(e) =>
+ guardCondOpt.fold(e) { cond =>
+ If(cond, e, Literal.create(null, e.dataType))
+ }
case e => nullify(e)
} :+ id
@@ -419,6 +481,104 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan] {
}
}
+ /**
+ * Canonicalizes COUNT(DISTINCT IF(cond, base, NULL)) and
+ * COUNT(DISTINCT CASE WHEN cond THEN base END) to COUNT(DISTINCT base) FILTER (WHERE cond).
+ * Multiple conditional counts on the same base then share one distinct group, shrinking
+ * Expand fan-out from Nx to 1x. [[rewrite]] only keeps this form when it strictly
+ * reduces the number of distinct groups.
+ *
+ * With the union-of-filters guard enabled, an all-filtered group whose children
+ * pass [[ExprUtils.canEvaluateUnconditionally]] projects `IF(Or(conds), base, NULL)`.
+ * `base` then runs on the union of the member filters: a row where some `cond_i`
+ * holds, which is a row whose original `IF(cond_i, base, NULL)` already evaluated
+ * `base`. The guard does not apply when any filter is non-deterministic, contains
+ * a subquery, or when a child fails that check (a user-written FILTER on a
+ * division, for example). Expand then projects the raw child on every row. A group
+ * that also has an unfiltered aggregate on the same base projects the raw base
+ * for every row too, matching the uncollapsed plan, which already evaluated it
+ * for that unfiltered member.
+ *
+ * A condition that itself contains a subquery is not normalized. Guarding that
+ * group would duplicate the predicate into a second existence join, and collapsing
+ * it without the guard would project the raw base.
+ *
+ * A count whose IF/CASE child is also the distinct child of an aggregate that is
+ * not normalized (e.g. SUM(DISTINCT IF(...)) on the same expression) is skipped:
+ * collapsing it would duplicate that child across the guarded {base} group and
+ * the surviving shared group, inflating the first aggregate's output for rows
+ * matching its condition. Keeping the count in the shared group preserves the
+ * original key sharing.
+ */
+ private def normalizeCountDistinctConditional(a: Aggregate): Aggregate = {
+ if (!SQLConf.get.rewriteCountDistinctConditionalEnabled) return a
+ // Distinct children (canonicalized) of aggregates this method will not
+ // normalize. A conditional count sharing one of these children stays put, so
+ // the shared group survives instead of its keys being carried twice.
+ val protectedChildren = collectAggregateExprs(a)
+ .filter(ae => ae.isDistinct && !isConditionalCount(ae))
+ .flatMap(_.aggregateFunction.children.map(_.canonicalized))
+ .toSet
+ a.transformExpressionsUpWithPruning(
+ _.containsAnyPattern(IF, CASE_WHEN)) {
+ case ae @ AggregateExpression(count: Count, _, true, None, _)
+ if count.children.size == 1 &&
+ !protectedChildren.contains(count.children.head.canonicalized) =>
+ extractCondAndBase(count.children.head) match {
+ case Some((cond, base)) =>
+ ae.copy(
+ aggregateFunction = Count(base),
+ filter = Some(cond))
+ case None => ae
+ }
+ }
+ }
+
+ /**
+ * Whether `ae` is a COUNT(DISTINCT IF/CASE) that
+ * [[normalizeCountDistinctConditional]] can canonicalize to FILTER form.
+ */
+ private def isConditionalCount(ae: AggregateExpression): Boolean = ae match {
+ case AggregateExpression(count: Count, _, true, None, _) if count.children.size == 1 =>
+ extractCondAndBase(count.children.head).isDefined
+ case _ => false
+ }
+
+ /**
+ * Matches IF(cond, base, null), CASE WHEN cond THEN base END, and
+ * CASE WHEN cond THEN base ELSE NULL END (including null wrapped in Cast).
+ * Multi-branch CaseWhen is intentionally not rewritten -- Or-flattening is out of scope.
+ * The base must pass [[ExprUtils.canEvaluateUnconditionally]]. The condition must
+ * not contain a subquery: normalizing one would merge the counts into a group
+ * that cannot be guarded, so Expand would project the raw base. The condition
+ * needs no [[ExprUtils.canEvaluateUnconditionally]] check, because it is already
+ * evaluated unconditionally as the IF/CASE WHEN predicate. A non-deterministic
+ * filter skips the guard and the raw base is projected for every row
+ * (see [[normalizeCountDistinctConditional]]).
+ * Returns None for anything else.
+ */
+ private def extractCondAndBase(expr: Expression): Option[(Expression, Expression)] = {
+ def eligible(cond: Expression, base: Expression): Boolean = {
+ !cond.containsPattern(PLAN_EXPRESSION) && ExprUtils.canEvaluateUnconditionally(base)
+ }
+
+ expr match {
+ case If(cond, base, e) if isNullExpr(e) && eligible(cond, base) =>
+ Some((cond, base))
+ case CaseWhen(Seq((cond, base)), None) if eligible(cond, base) =>
+ Some((cond, base))
+ case CaseWhen(Seq((cond, base)), Some(e)) if isNullExpr(e) && eligible(cond, base) =>
+ Some((cond, base))
+ case _ => None
+ }
+ }
+
+ private def isNullExpr(e: Expression): Boolean = e match {
+ case Literal(null, _) => true
+ case Cast(child, _, _, _) => isNullExpr(child)
+ case _ => false
+ }
+
private def collectAggregateExprs(a: Aggregate): Seq[AggregateExpression] = {
// Collect all aggregate expressions.
a.aggregateExpressions.flatMap { _.collect {
diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
index 676b4fb0c691..305a91eaa0b6 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
@@ -3377,6 +3377,35 @@ object SQLConf {
"The threshold must be >= 2 or -1 (disabled)")
.createWithDefault(-1)
+ val REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED =
+ buildConf("spark.sql.optimizer.rewriteCountDistinctConditional.enabled")
+ .internal()
+ .doc("When true, rewrites COUNT(DISTINCT IF(cond, base, NULL)) and " +
+ "COUNT(DISTINCT CASE WHEN cond THEN base END) into " +
+ "COUNT(DISTINCT base) FILTER (WHERE cond). This reduces the Expand factor " +
+ "in RewriteDistinctAggregates from Nx to 1x when multiple conditional distinct " +
+ "counts share the same base column. Also guards the shared distinct Expand " +
+ "key with the union of the filters (IF(Or(cond1, ..., condN), base, NULL)) " +
+ "for an all-filtered distinct group whose filters are deterministic and " +
+ "subquery-free and whose children are safe to evaluate unconditionally " +
+ "(including user-written FILTER on a plain column), so the first " +
+ "aggregate's output cardinality stays bounded by the un-rewritten " +
+ "plan. A child that is not safe to evaluate unconditionally (for example " +
+ "a division, which can throw) keeps the raw Expand key. When false, both " +
+ "the IF/CASE rewrite and the union-of-filters guard are disabled. The " +
+ "IF/CASE rewrite is only applied to base expressions that are safe to " +
+ "evaluate unconditionally (e.g. plain columns), so the short-circuit " +
+ "semantics of IF/CASE WHEN are preserved. A condition that contains a " +
+ "subquery is not rewritten. When spark.sql.optimizer.optimizeExpandRatio " +
+ "enables OptimizeExpand, the normalized FILTER form is not eligible for " +
+ "pre-aggregation because Expand projects filter flags. Enabling both can " +
+ "therefore trade lower Expand fan-out for losing pre-aggregation on " +
+ "duplicate-heavy inputs (SPARK-60318).")
+ .version("4.4.0")
+ .withBindingPolicy(ConfigBindingPolicy.SESSION)
+ .booleanConf
+ .createWithDefault(true)
+
val REMOVE_REDUNDANT_PROJECTS_ENABLED = buildConf("spark.sql.execution.removeRedundantProjects")
.internal()
.doc("Whether to remove redundant project exec node based on children's output and " +
@@ -9461,6 +9490,9 @@ class SQLConf extends Serializable with Logging with SqlApiConf {
def subqueryReuseEnabled: Boolean = getConf(SUBQUERY_REUSE_ENABLED)
+ def rewriteCountDistinctConditionalEnabled: Boolean =
+ getConf(REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED)
+
override def caseSensitiveAnalysis: Boolean = getConf(SQLConf.CASE_SENSITIVE)
def constraintPropagationEnabled: Boolean = getConf(CONSTRAINT_PROPAGATION_ENABLED)
diff --git a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala
index 08dd4011f04d..a627d00d20a7 100644
--- a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala
+++ b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala
@@ -18,11 +18,12 @@ 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.{Literal, Round}
-import org.apache.spark.sql.catalyst.expressions.aggregate.CollectSet
+import org.apache.spark.sql.catalyst.expressions.{AttributeReference, CaseWhen, Cast, Coalesce, Exists, Expression, GetMapValue, GetStructField, If, InSubquery, ListQuery, Literal, Lower, Not, Or, Rand, Round}
+import org.apache.spark.sql.catalyst.expressions.aggregate.{AggregateExpression, CollectSet, Count, Sum}
import org.apache.spark.sql.catalyst.plans.PlanTest
import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, Expand, LocalRelation, LogicalPlan}
-import org.apache.spark.sql.types.{IntegerType, StringType}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{DoubleType, IntegerType, MapType, StringType, StructField, StructType}
class RewriteDistinctAggregatesSuite extends PlanTest {
val nullInt = Literal(null, IntegerType)
@@ -125,4 +126,713 @@ class RewriteDistinctAggregatesSuite extends PlanTest {
fail(s"Plan is not as expected:\n$rewrite")
}
}
+
+ // ---------------------------------------------------------------------------
+ // COUNT(DISTINCT IF/CASE) canonicalization (SPARK-56898)
+ // ---------------------------------------------------------------------------
+
+ val conditionalTestRelation = 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 = CaseWhen(
+ Seq((cond, base)),
+ None)
+ Count(caseWhen).toAggregateExpression(isDistinct = true)
+ }
+
+ private def countDistinctCaseWhenElseNull(cond: Expression, base: Expression): Expression = {
+ val caseWhen = CaseWhen(
+ Seq((cond, base)),
+ Some(Literal(null)))
+ Count(caseWhen).toAggregateExpression(isDistinct = true)
+ }
+
+ private def collectAggregateExpressions(plan: LogicalPlan): Seq[AggregateExpression] = {
+ plan.collect { case a: Aggregate => a.aggregateExpressions }
+ .flatten
+ .flatMap(_.collect { case ae: AggregateExpression => ae })
+ }
+
+ /**
+ * Asserts that the optimized plan has exactly one Expand node with one projection,
+ * that the shared distinct key is guarded by the union of the member filters,
+ * and that the outer aggregate has moved the conditions into FILTER clauses.
+ */
+ private def assertSingleDistinctGroupExpand(
+ optimized: LogicalPlan,
+ baseColName: String,
+ conds: Seq[Expression]): Unit = {
+ // rewrite() adds EqualTo(gid, id) to every distinct aggregate, so filter.isDefined
+ // alone always passes. Require a user-condition reference (same as assertCanonicalized).
+ val hasUserConditionFilter = collectAggregateExpressions(optimized)
+ .flatMap(_.filter)
+ .exists(_.references.exists(_.name != "gid"))
+ assert(hasUserConditionFilter,
+ "expected at least one AggregateExpression with a user-condition FILTER clause")
+ val baseAttr = conditionalTestRelation.output.find(_.name == baseColName).get
+ assertGuardedExpandKey(optimized, baseAttr, conds)
+ }
+
+ /**
+ * Asserts that the collapsed distinct group's Expand key is guarded by the union
+ * of the member filters, i.e. IF(Or(cond1, ..., condN), base, NULL): rows matching
+ * no predicate project NULL as the distinct key and collapse into a single key in
+ * the first aggregate, keeping its output cardinality bounded by the pre-rewrite
+ * plan (distinct(base | Or(conds)) + 1 <= sum_i distinct(base | cond_i) + N).
+ */
+ private def assertGuardedExpandKey(
+ optimized: LogicalPlan,
+ base: Expression,
+ conds: Seq[Expression]): Unit = {
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ assert(expand.projections.size == 1,
+ s"expected 1 distinct group but got ${expand.projections.size}")
+ val guard = expand.projections.head.collectFirst {
+ case i @ If(_, trueValue, falseValue)
+ if falseValue == nullInt && trueValue.semanticEquals(base) => i
+ }.getOrElse(fail(s"no union guard over $base in Expand projections:\n$optimized"))
+ val leaves = orLeaves(guard.predicate)
+ assert(leaves.size == conds.size,
+ s"guard condition should cover all ${conds.size} filters: ${guard.predicate}")
+ conds.foreach { c =>
+ assert(leaves.exists(_.semanticEquals(c)),
+ s"guard condition misses $c: ${guard.predicate}")
+ }
+ }
+
+ private def orLeaves(expr: Expression): Seq[Expression] = expr match {
+ case Or(left, right) => orLeaves(left) ++ orLeaves(right)
+ case other => Seq(other)
+ }
+
+ /** EXISTS / IN / NOT IN nodes in Expand projections. The guard must not copy these. */
+ private def subqueryExprCount(plan: LogicalPlan): Int = {
+ val exprs = plan.collect { case e: Expand => e }.flatMap(_.projections.flatten)
+ exprs.map(_.collect { case _: Exists | _: InSubquery => () }.size).sum
+ }
+
+ test("conditional: disabled when config is false") {
+ withSQLConf(SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "false") {
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ countDistinctIf(Symbol("b") > 1, Symbol("c")).as("cnt1"),
+ countDistinctIf(Symbol("b") > 2, Symbol("c")).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ // The general RewriteDistinctAggregates still fires, but conditional
+ // canonicalization is disabled so the two conditional counts stay as 2
+ // distinct groups instead of collapsing to 1.
+ val expands = optimized.collect { case e: Expand => e }
+ assert(expands.head.projections.size == 2,
+ "expected 2 distinct groups when conditional canonicalization is disabled")
+ }
+ }
+
+ test("conditional: rewrite COUNT(DISTINCT IF(cond, col, NULL)) to COUNT(DISTINCT col) FILTER") {
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ countDistinctIf(Symbol("b") > 1, Symbol("c")).as("cnt1"),
+ countDistinctIf(Symbol("b") > 2, Symbol("c")).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ assertSingleDistinctGroupExpand(optimized, "c", Seq(bAttr > 1, bAttr > 2))
+ }
+
+ test("conditional: rewrite COUNT(DISTINCT CASE WHEN cond THEN col END) to " +
+ "COUNT(DISTINCT col) FILTER") {
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ countDistinctCaseWhen(Symbol("b") > 1, Symbol("c")).as("cnt1"),
+ countDistinctCaseWhen(Symbol("b") > 2, Symbol("c")).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ assertSingleDistinctGroupExpand(optimized, "c", Seq(bAttr > 1, bAttr > 2))
+ }
+
+ test("conditional: rewrite COUNT(DISTINCT CASE WHEN cond THEN col ELSE NULL END)") {
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ countDistinctCaseWhenElseNull(Symbol("b") > 1, Symbol("c")).as("cnt1"),
+ countDistinctCaseWhenElseNull(Symbol("b") > 2, Symbol("c")).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ assertSingleDistinctGroupExpand(optimized, "c", Seq(bAttr > 1, bAttr > 2))
+ }
+
+ test("conditional: multiple conditional distinct counts collapse to single distinct group") {
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val input = conditionalTestRelation
+ .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
+ val optimized = RewriteDistinctAggregates(input)
+ // All three counts share the same base column c, collapsed to 1 distinct group.
+ assertSingleDistinctGroupExpand(
+ optimized, "c", Seq(bAttr > 1, bAttr > 2, bAttr > 3))
+ }
+
+ test("conditional: guarded Expand key is IF(union of conditions, base, NULL)") {
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val base = conditionalTestRelation.output.find(_.name == "c").get
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ countDistinctIf(Symbol("b") > 1, Symbol("c")).as("cnt1"),
+ countDistinctIf(Symbol("b") > 2, Symbol("c")).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ assertGuardedExpandKey(optimized, base, Seq(bAttr > 1, bAttr > 2))
+ }
+
+ test("conditional: guarded Expand key covers CASE WHEN conditions too") {
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val base = conditionalTestRelation.output.find(_.name == "c").get
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ countDistinctCaseWhen(Symbol("b") > 1, Symbol("c")).as("cnt1"),
+ countDistinctCaseWhenElseNull(Symbol("b") > 2, Symbol("c")).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ assertGuardedExpandKey(optimized, base, Seq(bAttr > 1, bAttr > 2))
+ }
+
+ test("conditional: guarded Expand key covers all conditions of a 3-count collapse") {
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val base = conditionalTestRelation.output.find(_.name == "c").get
+ val input = conditionalTestRelation
+ .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
+ val optimized = RewriteDistinctAggregates(input)
+ assertGuardedExpandKey(optimized, base, Seq(bAttr > 1, bAttr > 2, bAttr > 3))
+ }
+
+ test("conditional: user-written FILTER counts sharing a base get the union guard") {
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val base = conditionalTestRelation.output.find(_.name == "c").get
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(base).toAggregateExpression(isDistinct = true, filter = Some(bAttr > 1)).as("cnt1"),
+ Count(base).toAggregateExpression(isDistinct = true, filter = Some(bAttr > 2)).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ assertGuardedExpandKey(optimized, base, Seq(bAttr > 1, bAttr > 2))
+ }
+
+ test("conditional: config false disables union guard for user-written FILTER") {
+ // The config is the kill switch for both IF/CASE normalize and the union-of-filters
+ // guard. With it off, user-written FILTER distincts still Expand (mustRewrite) but
+ // keep the raw base as the Expand key.
+ withSQLConf(SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "false") {
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val base = conditionalTestRelation.output.find(_.name == "c").get
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(base).toAggregateExpression(isDistinct = true, filter = Some(bAttr > 1))
+ .as("cnt1"),
+ Count(base).toAggregateExpression(isDistinct = true, filter = Some(bAttr > 2))
+ .as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ assert(expand.projections.size == 1)
+ assert(expand.projections.head.exists(_.semanticEquals(base)),
+ "raw base expected when rewriteCountDistinctConditional is disabled")
+ assert(
+ !expand.projections.head.exists {
+ case If(_, trueValue, falseValue) =>
+ falseValue == nullInt && trueValue.semanticEquals(base)
+ case _ => false
+ },
+ "union guard should be off when rewriteCountDistinctConditional is disabled")
+ }
+ }
+
+ test("conditional: unfiltered count in the group keeps the raw base key") {
+ val base = conditionalTestRelation.output.find(_.name == "c").get
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(base).toAggregateExpression(isDistinct = true).as("cnt0"),
+ Count(base).toAggregateExpression(isDistinct = true,
+ filter = Some(Symbol("b") > 1)).as("cnt1"),
+ Count(base).toAggregateExpression(isDistinct = true,
+ filter = Some(Symbol("b") > 2)).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ // One distinct group {c}, but the unfiltered count needs the raw child over all
+ // rows, so the Expand key must not be guarded.
+ assert(expand.projections.size == 1)
+ assert(expand.projections.head.exists(_.semanticEquals(base)),
+ "raw base attribute expected when the group contains an unfiltered count")
+ }
+
+ test("conditional: non-deterministic filter keeps the raw base key") {
+ val base = conditionalTestRelation.output.find(_.name == "c").get
+ val nondet = Rand(42) < Literal(0.5, DoubleType)
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(base).toAggregateExpression(isDistinct = true, filter = Some(nondet)).as("cnt1"),
+ Count(base).toAggregateExpression(isDistinct = true, filter = Some(nondet)).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ // The guard re-evaluates the filters, so non-deterministic ones must not be
+ // guarded; the Expand key stays the raw attribute.
+ assert(expand.projections.head.exists(_.semanticEquals(base)),
+ "raw base attribute expected with a non-deterministic filter")
+ }
+
+ test("conditional: EXISTS, IN, and NOT IN filters keep the raw key") {
+ // RewritePredicateSubquery has not run. Copying a predicate subquery into the
+ // Expand key builds a second ExistenceJoin later, so the key stays raw and each
+ // predicate appears once, as its flag column.
+ val dim = LocalRelation(Symbol("x").int)
+ val existsPred = Exists(dim)
+ val inPred = InSubquery(Seq(Symbol("b")), ListQuery(dim, numCols = 1))
+ val notInPred = Not(InSubquery(Seq(Symbol("c")), ListQuery(dim, numCols = 1)))
+ val b = conditionalTestRelation.output.find(_.name == "b").get
+ val c = conditionalTestRelation.output.find(_.name == "c").get
+ val d = conditionalTestRelation.output.find(_.name == "d").get
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(b).toAggregateExpression(isDistinct = true, filter = Some(existsPred)).as("cnt1"),
+ Count(c).toAggregateExpression(isDistinct = true, filter = Some(inPred)).as("cnt2"),
+ Count(d).toAggregateExpression(isDistinct = true, filter = Some(notInPred)).as("cnt3"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ assert(expand.projections.size == 3)
+ Seq(b, c, d).foreach { base =>
+ val nullOfBase = Literal.create(null, base.dataType)
+ assert(expand.projections.exists(_.exists(_.semanticEquals(base))),
+ s"raw key expected for $base")
+ assert(!expand.projections.exists(_.exists {
+ case If(_, trueValue, falseValue) =>
+ falseValue.semanticEquals(nullOfBase) && trueValue.semanticEquals(base)
+ case _ => false
+ }), s"subquery filter must not guard $base")
+ }
+ assert(subqueryExprCount(optimized) == 3,
+ "each predicate subquery should appear once in the Expand")
+ }
+
+ test("conditional: do not canonicalize counts whose condition is a predicate subquery") {
+ // Normalizing would merge these into one group that cannot be guarded, and Expand
+ // would project the raw base. Leave each IF/CASE in its own group.
+ val dim = LocalRelation(Symbol("x").int)
+ val x = dim.output.head
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ countDistinctIf(Exists(dim.where(x > 0)), Symbol("c")).as("cnt1"),
+ countDistinctCaseWhen(Exists(dim.where(x > 1)), Symbol("c")).as("cnt2"),
+ countDistinctCaseWhenElseNull(Exists(dim.where(x > 2)), Symbol("c")).as("cnt3"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ assert(expand.projections.size == 3,
+ "subquery conditions should stay 3 distinct groups")
+ val hasUserConditionFilter = collectAggregateExpressions(optimized)
+ .flatMap(_.filter)
+ .exists(_.references.exists(_.name != "gid"))
+ assert(!hasUserConditionFilter,
+ "subquery condition should not become a user-condition FILTER clause")
+ assert(subqueryExprCount(optimized) == 3,
+ "each predicate subquery should appear once in the Expand")
+ }
+
+ test("conditional: subquery-free filters stay guarded beside a subquery condition") {
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val base = conditionalTestRelation.output.find(_.name == "c").get
+ val dim = LocalRelation(Symbol("x").int)
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ countDistinctIf(Symbol("b") > 1, Symbol("c")).as("cnt1"),
+ countDistinctIf(Symbol("b") > 2, Symbol("c")).as("cnt2"),
+ countDistinctIf(Exists(dim), Symbol("c")).as("cnt3"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ // The two plain predicates share one guarded group. The EXISTS count stays separate.
+ assert(expand.projections.size == 2)
+ val guard = expand.projections.flatten.collectFirst {
+ case i @ If(_, trueValue, falseValue)
+ if falseValue == nullInt && trueValue.semanticEquals(base) => i
+ }.getOrElse(fail(s"no union guard over c:\n$optimized"))
+ val leaves = orLeaves(guard.predicate)
+ assert(leaves.size == 2, s"guard should cover only the plain predicates: ${guard.predicate}")
+ Seq(bAttr > 1, bAttr > 2).foreach { cond =>
+ assert(leaves.exists(_.semanticEquals(cond)), s"guard misses $cond: ${guard.predicate}")
+ }
+ assert(subqueryExprCount(optimized) == 1,
+ "the EXISTS condition should appear once, in its own group")
+ }
+
+ test("conditional: throwable distinct child keeps the raw key") {
+ // Division can throw under ANSI on rows the filter rejects. Wrapping it in
+ // the guard would skip those evaluations, so the Expand key stays raw.
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(Symbol("c") / Symbol("b")).toAggregateExpression(
+ isDistinct = true, filter = Some(Symbol("a") > 0)).as("cnt"))
+ .analyze
+ val child = input.collectFirst {
+ case a: Aggregate =>
+ a.aggregateExpressions.flatMap(_.collect {
+ case ae: AggregateExpression if ae.isDistinct =>
+ ae.aggregateFunction.children.headOption
+ }).flatten.head
+ }.get
+ val optimized = RewriteDistinctAggregates(input)
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ assert(expand.projections.head.exists(_.semanticEquals(child)),
+ s"raw distinct child expected, projections:\n${expand.projections.head}")
+ }
+
+ test("conditional: single conditional distinct count is gated out by mayNeedtoRewrite") {
+ // A lone COUNT(DISTINCT IF(...)) must NOT be pushed onto the Expand path.
+ // The canonicalization runs inside rewrite(), which is only called when
+ // mayNeedtoRewrite returns true. A single conditional distinct count has no filter
+ // and forms only one distinct group, so mayNeedtoRewrite returns false, rewrite()
+ // is never called, and no Expand is produced.
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ countDistinctIf(Symbol("b") > 1, Symbol("c")).as("cnt1"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ val expands = optimized.collect { case e: Expand => e }
+ assert(expands.isEmpty, "single conditional distinct count should not produce an Expand")
+ }
+
+ test("conditional: COUNT+SUM sharing IF keeps single-distinct path") {
+ // Both share one unfiltered distinct child. Normalizing only the COUNT would
+ // split the group into {c} and {IF(b>1,c,NULL)} and force a 2-projection Expand.
+ // Keep the original aggregate so AggregationStrategy handles it without Expand.
+ // Use the same null literal as countDistinctIf so the IF children are one
+ // ExpressionSet key after analysis (as in SQL COUNT/SUM over the same IF).
+ val sharedIf = If(Symbol("b") > 1, Symbol("c"), Literal(null))
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(sharedIf).toAggregateExpression(isDistinct = true).as("cnt"),
+ Sum(sharedIf).toAggregateExpression(isDistinct = true).as("sum"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ comparePlans(optimized, input)
+ }
+
+ test("conditional: IF shared with an un-normalizable distinct agg is not normalized") {
+ // COUNT(DISTINCT IF(b>1, c, NULL)) shares its IF child with SUM(DISTINCT IF(...)),
+ // which is not canonicalized. Normalizing the COUNT would move it into the guarded
+ // {c} group while the SUM keeps the {IF(b>1, c, NULL)} group, so rows matching b>1
+ // would carry their c keys in both groups, roughly doubling the first aggregate's
+ // output. The count must stay in the shared group; only the other two conditional
+ // counts collapse, and their guard covers exactly b>2 and b>3.
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val base = conditionalTestRelation.output.find(_.name == "c").get
+ val sharedIf = If(Symbol("b") > 1, Symbol("c"), Literal(null))
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(sharedIf).toAggregateExpression(isDistinct = true).as("cnt1"),
+ Sum(sharedIf).toAggregateExpression(isDistinct = true).as("sum1"),
+ countDistinctIf(Symbol("b") > 2, Symbol("c")).as("cnt2"),
+ countDistinctIf(Symbol("b") > 3, Symbol("c")).as("cnt3"))
+ .analyze
+ // The resolved shared IF child of the un-normalized COUNT and SUM.
+ val analyzedSharedIf = input.collectFirst {
+ case a: Aggregate => a.aggregateExpressions.flatMap(_.collect {
+ case ae: AggregateExpression
+ if ae.isDistinct && ae.aggregateFunction.isInstanceOf[Sum] =>
+ ae.aggregateFunction.children.head
+ }).head
+ }.get
+ val optimized = RewriteDistinctAggregates(input)
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ // Two distinct groups: {IF(b>1, c, NULL)} serving cnt1 and sum1, and the guarded
+ // {c} group serving cnt2 and cnt3.
+ assert(expand.projections.size == 2,
+ s"expected 2 distinct groups:\n$optimized")
+ assert(expand.projections.exists(_.exists(_.semanticEquals(analyzedSharedIf))),
+ s"shared IF should stay a raw distinct key:\n$optimized")
+ // Skip the shared IF, whose trueValue is also c.
+ val guard = expand.projections.flatten.collectFirst {
+ case i @ If(_, trueValue, falseValue)
+ if falseValue == nullInt && trueValue.semanticEquals(base) &&
+ !i.semanticEquals(analyzedSharedIf) => i
+ }.getOrElse(fail(s"no union guard over c in Expand projections:\n$optimized"))
+ val leaves = orLeaves(guard.predicate)
+ assert(leaves.size == 2,
+ s"guard condition should cover exactly b>2 and b>3: ${guard.predicate}")
+ Seq(bAttr > 2, bAttr > 3).foreach { cond =>
+ assert(leaves.exists(_.semanticEquals(cond)),
+ s"guard condition misses $cond: ${guard.predicate}")
+ }
+ }
+
+ test("conditional: repeated COUNT(DISTINCT IF) with COUNT(*) keeps single-distinct path") {
+ // Two identical conditional counts form one unfiltered distinct group. Normalizing
+ // them to FILTER form would make mustRewrite true and introduce an Expand
+ // (regular branch + distinct branch) with no fan-out reduction.
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ countDistinctIf(Symbol("b") > 1, Symbol("c")).as("cnt"),
+ countDistinctIf(Symbol("b") > 1, Symbol("c")).as("cnt2"),
+ Count(Literal(1)).toAggregateExpression().as("n"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ comparePlans(optimized, input)
+ }
+
+ test("conditional: do not rewrite IF with non-null else branch") {
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(If(Symbol("b") > 1, Symbol("c"), Literal(0, IntegerType)))
+ .toAggregateExpression(isDistinct = true)
+ .as("cnt1"),
+ Count(If(Symbol("b") > 2, Symbol("c"), Literal(0, IntegerType)))
+ .toAggregateExpression(isDistinct = true)
+ .as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ // Plan is rewritten (2 distinct groups) but not canonicalized
+ checkRewrite(optimized)
+ val expands = optimized.collect { case e: Expand => e }
+ assert(expands.head.projections.size == 2,
+ "non-null else branch should not be collapsed to 1 distinct group")
+ }
+
+ test("conditional: do not rewrite CASE WHEN with non-null else branch") {
+ // ELSE NULL is removed by SimplifyConditionals before this rule, so the
+ // CaseWhen arm with an else is only reached for a non-null else. Rewriting
+ // it would drop that value and collapse both counts onto one guarded group.
+ val caseWhen1 = CaseWhen(
+ Seq((Symbol("b") > 1, Symbol("c"))),
+ Some(Literal(0, IntegerType)))
+ val caseWhen2 = CaseWhen(
+ Seq((Symbol("b") > 2, Symbol("c"))),
+ Some(Literal(0, IntegerType)))
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(caseWhen1).toAggregateExpression(isDistinct = true).as("cnt1"),
+ Count(caseWhen2).toAggregateExpression(isDistinct = true).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ // Plan is rewritten (2 distinct groups) but not canonicalized.
+ checkRewrite(optimized)
+ val expands = optimized.collect { case e: Expand => e }
+ assert(expands.head.projections.size == 2,
+ "non-null else branch should not be collapsed to 1 distinct group")
+ val hasUserConditionFilter = collectAggregateExpressions(optimized)
+ .flatMap(_.filter)
+ .exists(_.references.exists(_.name != "gid"))
+ assert(!hasUserConditionFilter,
+ "CASE WHEN with a non-null else must not gain a user-condition FILTER")
+ }
+
+ test("conditional: do not rewrite non-distinct COUNT") {
+ // Pair the non-distinct COUNT with two conditional distinct counts on the same
+ // base so that normalization is kept (strict reduction) and rewrite() runs.
+ // The non-distinct COUNT must keep its IF child and get no FILTER clause.
+ val bAttr = conditionalTestRelation.output.find(_.name == "b").get
+ val base = conditionalTestRelation.output.find(_.name == "c").get
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(If(Symbol("b") > 1, Symbol("c"), Literal(null, IntegerType)))
+ .toAggregateExpression(isDistinct = false)
+ .as("cnt"),
+ countDistinctIf(Symbol("b") > 1, Symbol("c")).as("cnt1"),
+ countDistinctIf(Symbol("b") > 2, Symbol("c")).as("cnt2"))
+ .analyze
+ // The resolved IF child of the non-distinct COUNT.
+ val analyzedIf = input.collectFirst {
+ case a: Aggregate => a.aggregateExpressions.flatMap(_.collect {
+ case ae: AggregateExpression if !ae.isDistinct =>
+ ae.aggregateFunction.children.head
+ }).head
+ }.get
+ val optimized = RewriteDistinctAggregates(input)
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ // One regular projection plus one distinct projection: the two conditional
+ // distinct counts collapsed into a single guarded distinct group.
+ assert(expand.projections.size == 2,
+ s"expected 1 regular + 1 distinct projection:\n$optimized")
+ // The guard lives in the distinct projection; skip the non-distinct COUNT's own
+ // IF, which is projected raw in the regular projection.
+ val guard = expand.projections.flatten.collectFirst {
+ case i @ If(_, trueValue, falseValue)
+ if falseValue == nullInt && trueValue.semanticEquals(base) &&
+ !i.semanticEquals(analyzedIf) => i
+ }.getOrElse(fail(s"no union guard over c in Expand projections:\n$optimized"))
+ val leaves = orLeaves(guard.predicate)
+ assert(leaves.size == 2,
+ s"guard condition should cover both filters: ${guard.predicate}")
+ Seq(bAttr > 1, bAttr > 2).foreach { cond =>
+ assert(leaves.exists(_.semanticEquals(cond)),
+ s"guard condition misses $cond: ${guard.predicate}")
+ }
+ // The non-distinct COUNT keeps its IF child in the regular projection.
+ assert(expand.projections.exists(_.exists(_.semanticEquals(analyzedIf))),
+ s"non-distinct COUNT should keep its IF child in the Expand:\n$optimized")
+ // ... and gains no FILTER clause in the first aggregate.
+ val innerAgg = optimized.collectFirst {
+ case a @ Aggregate(_, _, _: Expand, _) => a
+ }.get
+ val nonDistinctCounts = collectAggregateExpressions(innerAgg).filter { ae =>
+ !ae.isDistinct && ae.aggregateFunction.isInstanceOf[Count]
+ }
+ assert(nonDistinctCounts.size == 1)
+ assert(nonDistinctCounts.head.filter.isEmpty,
+ "non-distinct COUNT must not gain a FILTER clause")
+ }
+
+ test("conditional: do not rewrite when FILTER already exists") {
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(If(Symbol("b") > 1, Symbol("c"), Literal(null, IntegerType)))
+ .toAggregateExpression(isDistinct = true, filter = Some(Symbol("d") === "x"))
+ .as("cnt1"),
+ Count(If(Symbol("b") > 2, Symbol("c"), Literal(null, IntegerType)))
+ .toAggregateExpression(isDistinct = true, filter = Some(Symbol("d") === "y"))
+ .as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ checkRewrite(optimized)
+ val expands = optimized.collect { case e: Expand => e }
+ // 2 groups because existing FILTERs prevent canonicalization
+ assert(expands.head.projections.size == 2)
+ }
+
+ test("conditional: do not rewrite multi-branch CASE WHEN") {
+ val caseWhen1 = new CaseWhen(
+ Seq(
+ (Symbol("b") > Literal(1), Symbol("c")),
+ (Symbol("b") > Literal(2), Symbol("a"))),
+ Some(Literal(null)))
+ val caseWhen2 = new CaseWhen(
+ Seq(
+ (Symbol("b") > Literal(3), Symbol("c")),
+ (Symbol("b") > Literal(4), Symbol("a"))),
+ Some(Literal(null)))
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Count(caseWhen1).toAggregateExpression(isDistinct = true).as("cnt1"),
+ Count(caseWhen2).toAggregateExpression(isDistinct = true).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ checkRewrite(optimized)
+ val expands = optimized.collect { case e: Expand => e }
+ // 2 groups - multi-branch CASE was not canonicalized
+ assert(expands.head.projections.size == 2)
+ }
+
+ test("conditional: do not rewrite SUM(DISTINCT IF(...))") {
+ val input = conditionalTestRelation
+ .groupBy(Symbol("a"))(
+ Sum(If(Symbol("b") > 1, Symbol("c"), Literal(null, IntegerType)))
+ .toAggregateExpression(isDistinct = true)
+ .as("sum1"),
+ Sum(If(Symbol("b") > 2, Symbol("c"), Literal(null, IntegerType)))
+ .toAggregateExpression(isDistinct = true)
+ .as("sum2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ checkRewrite(optimized)
+ val expands = optimized.collect { case e: Expand => e }
+ // 2 groups - SUM(DISTINCT IF) is not canonicalized
+ assert(expands.head.projections.size == 2)
+ }
+
+ /**
+ * Asserts that two conditional distinct counts over `base` collapse into a single
+ * distinct group with a FILTER clause, i.e. the conditional canonicalization fired.
+ */
+ private def assertCanonicalized(relation: LocalRelation, base: Expression): Unit = {
+ val input = relation
+ .groupBy(Symbol("a"))(
+ countDistinctIf(Symbol("b") > 1, base).as("cnt1"),
+ countDistinctIf(Symbol("b") > 2, base).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ assert(expand.projections.size == 1,
+ s"branch-safe base should collapse to 1 distinct group: $base")
+ // The Expand rewrite adds gid-routing filters to every distinct aggregate; the
+ // canonicalization additionally introduces filters referencing the user condition.
+ val hasUserConditionFilter = collectAggregateExpressions(optimized)
+ .flatMap(_.filter)
+ .exists(_.references.exists(_.name != "gid"))
+ assert(hasUserConditionFilter,
+ s"expected a user-condition FILTER clause after canonicalizing base: $base")
+ }
+
+ /**
+ * Asserts that two conditional distinct counts over `base` are rewritten by the
+ * general Expand path but are NOT canonicalized, i.e. they stay 2 distinct groups
+ * and no FILTER clause is introduced.
+ */
+ private def assertNotCanonicalized(relation: LocalRelation, base: Expression): Unit = {
+ val input = relation
+ .groupBy(Symbol("a"))(
+ countDistinctIf(Symbol("b") > 1, base).as("cnt1"),
+ countDistinctIf(Symbol("b") > 2, base).as("cnt2"))
+ .analyze
+ val optimized = RewriteDistinctAggregates(input)
+ checkRewrite(optimized)
+ val expand = optimized.collectFirst { case e: Expand => e }.get
+ assert(expand.projections.size == 2,
+ s"non-branch-safe base should stay 2 distinct groups: $base")
+ // The Expand rewrite adds gid-routing filters to every distinct aggregate; a
+ // user-condition filter introduced by the canonicalization would reference the
+ // condition's columns instead of only gid.
+ val hasUserConditionFilter = collectAggregateExpressions(optimized)
+ .flatMap(_.filter)
+ .exists(_.references.exists(_.name != "gid"))
+ assert(!hasUserConditionFilter,
+ s"non-branch-safe base should not produce a user-condition FILTER clause: $base")
+ }
+
+ test("conditional: do not rewrite when base is not branch-safe") {
+ val unsafeBases = Seq(
+ // Division may throw (e.g. divide-by-zero under ANSI mode) on rows where the
+ // original IF branch is not taken.
+ Symbol("c") / Symbol("b"),
+ // Cast may throw under ANSI mode.
+ Cast(Symbol("c"), StringType),
+ // String functions are not in the branch-safe whitelist.
+ Lower(Symbol("d")))
+ unsafeBases.foreach { base =>
+ assertNotCanonicalized(conditionalTestRelation, base)
+ }
+ }
+
+ test("conditional: rewrite branch-safe expression bases") {
+ // Predicate and null-handling bases on the flat test relation.
+ Seq(
+ Symbol("b") > Symbol("c"),
+ Coalesce(Seq(Symbol("b"), Literal(0, IntegerType))))
+ .foreach { base =>
+ assertCanonicalized(conditionalTestRelation, base)
+ }
+
+ // Total accessor bases need struct/map attributes.
+ val structAttr = AttributeReference("s", StructType(Seq(StructField("f", IntegerType))))()
+ val mapAttr = AttributeReference("m", MapType(IntegerType, StringType))()
+ val richRelation = LocalRelation(Symbol("a").int, Symbol("b").int, structAttr, mapAttr)
+ Seq(
+ GetStructField(structAttr, 0),
+ GetMapValue(mapAttr, Literal(1, IntegerType)))
+ .foreach { base =>
+ assertCanonicalized(richRelation, base)
+ }
+ }
}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/RewriteDistinctAggregatesConditionalQuerySuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/RewriteDistinctAggregatesConditionalQuerySuite.scala
new file mode 100644
index 000000000000..0ce7bd44001c
--- /dev/null
+++ b/sql/core/src/test/scala/org/apache/spark/sql/RewriteDistinctAggregatesConditionalQuerySuite.scala
@@ -0,0 +1,533 @@
+/*
+ * 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
+
+import org.apache.spark.sql.catalyst.expressions.{Expression, If, Or}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.plans.ExistenceJoin
+import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, Expand, Join, LogicalPlan}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+
+class RewriteDistinctAggregatesConditionalQuerySuite extends QueryTest with SharedSparkSession {
+
+ private def checkRewriteAndResult(
+ conditionalSql: String,
+ filterSql: String): Unit = {
+ val expectedRows = spark.sql(filterSql).collect()
+
+ // Verify the rewrite produces the same result as the explicit FILTER form.
+ withSQLConf(
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "true") {
+ checkAnswer(spark.sql(conditionalSql), expectedRows)
+ }
+
+ // Verify the non-rewritten form also matches the explicit FILTER form.
+ withSQLConf(
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "false") {
+ checkAnswer(spark.sql(conditionalSql), expectedRows)
+ }
+ }
+
+ private def hasUserConditionFilter(plan: LogicalPlan): Boolean = {
+ val aggregateExpressions = plan.collect {
+ case a: Aggregate => a.aggregateExpressions
+ }.flatten
+ val aggregateExprs = aggregateExpressions.flatMap {
+ _.collect { case ae: AggregateExpression => ae }
+ }
+ // The Expand rewrite adds gid-routing filters to every distinct aggregate; we only
+ // care about user-condition filters introduced by the IF/CASE canonicalization.
+ aggregateExprs.flatMap(_.filter).exists(_.references.exists(_.name != "gid"))
+ }
+
+ private def orLeaves(expr: Expression): Seq[Expression] = expr match {
+ case Or(left, right) => orLeaves(left) ++ orLeaves(right)
+ case other => Seq(other)
+ }
+
+ private def existenceJoinCount(plan: LogicalPlan): Int = {
+ plan.collect { case Join(_, _, _: ExistenceJoin, _, _) => () }.size
+ }
+
+ /**
+ * Conf on must keep the conf-off ExistenceJoin count. The union guard copies each
+ * filter into the Expand key, and RewritePredicateSubquery builds one join per copy.
+ * When `stayUnnormalized` is set, the IF/CASE condition must not become a FILTER.
+ */
+ private def assertSameExistenceJoinCount(
+ sqlText: String,
+ expectedJoins: Int,
+ stayUnnormalized: Boolean = false): Unit = {
+ val (expectedRows, joinsOff) = withSQLConf(
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "false") {
+ val df = spark.sql(sqlText)
+ (df.collect(), existenceJoinCount(df.queryExecution.optimizedPlan))
+ }
+ assert(joinsOff == expectedJoins,
+ s"conf off produced $joinsOff existence joins, expected $expectedJoins")
+ withSQLConf(
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "true") {
+ val df = spark.sql(sqlText)
+ checkAnswer(df, expectedRows)
+ val plan = df.queryExecution.optimizedPlan
+ val joinsOn = existenceJoinCount(plan)
+ assert(joinsOn == expectedJoins,
+ s"conf on produced $joinsOn existence joins, expected $expectedJoins:\n$plan")
+ if (stayUnnormalized) {
+ assert(!hasUserConditionFilter(plan),
+ "predicate-subquery condition should not become a FILTER clause")
+ }
+ }
+ }
+
+ test("rewrite COUNT(DISTINCT IF(cond, col, NULL)) correctness") {
+ withTempView("t") {
+ spark.range(7)
+ .selectExpr(
+ "cast(id % 3 + 1 as int) as key",
+ "cast(id * 10 as int) as col1",
+ "case when id % 4 = 0 then null else cast(id * 100 as int) end as col2")
+ .createOrReplaceTempView("t")
+
+ // Two conditional distinct counts on the same base so the rewrite fires (size > 1).
+ checkRewriteAndResult(
+ """SELECT key,
+ | COUNT(DISTINCT IF(col1 > 10, col2, NULL)),
+ | COUNT(DISTINCT IF(col1 > 20, col2, NULL))
+ |FROM t GROUP BY key""".stripMargin,
+ """SELECT key,
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 10),
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 20)
+ |FROM t GROUP BY key""".stripMargin)
+ }
+ }
+
+ test("rewrite COUNT(DISTINCT CASE WHEN cond THEN col END) correctness") {
+ withTempView("t") {
+ spark.range(7)
+ .selectExpr(
+ "cast(id % 3 + 1 as int) as key",
+ "cast(id * 10 as int) as col1",
+ "case when id % 4 = 0 then null else cast(id * 100 as string) end as col2")
+ .createOrReplaceTempView("t")
+
+ // Two CASE WHEN conditional distinct counts on the same base so the rewrite fires.
+ checkRewriteAndResult(
+ """SELECT key,
+ | COUNT(DISTINCT CASE WHEN col1 > 10 THEN col2 END),
+ | COUNT(DISTINCT CASE WHEN col1 > 20 THEN col2 END)
+ |FROM t GROUP BY key""".stripMargin,
+ """SELECT key,
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 10),
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 20)
+ |FROM t GROUP BY key""".stripMargin)
+ }
+ }
+
+ test("rewrite COUNT(DISTINCT CASE WHEN cond THEN col ELSE NULL END) correctness") {
+ withTempView("t") {
+ spark.range(6)
+ .selectExpr(
+ "cast(id % 2 + 1 as int) as key",
+ "cast(id * 10 as int) as col1",
+ "case when id % 4 = 0 then null else cast(id * 1.0 as double) end as col2")
+ .createOrReplaceTempView("t")
+
+ // Two CASE WHEN ... ELSE NULL counts on the same base so the rewrite fires.
+ checkRewriteAndResult(
+ """SELECT key,
+ | COUNT(DISTINCT CASE WHEN col1 > 10 THEN col2 ELSE NULL END),
+ | COUNT(DISTINCT CASE WHEN col1 > 20 THEN col2 ELSE NULL END)
+ |FROM t GROUP BY key""".stripMargin,
+ """SELECT key,
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 10),
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 20)
+ |FROM t GROUP BY key""".stripMargin)
+ }
+ }
+
+ test("rewrite with no GROUP BY") {
+ withTempView("t") {
+ spark.range(5)
+ .selectExpr(
+ "cast(id * 10 as int) as col1",
+ "case when id % 3 = 0 then null else cast(id * 100 as int) end as col2")
+ .createOrReplaceTempView("t")
+
+ // Two counts so the rewrite fires without GROUP BY.
+ checkRewriteAndResult(
+ """SELECT
+ | COUNT(DISTINCT IF(col1 > 10, col2, NULL)),
+ | COUNT(DISTINCT IF(col1 > 20, col2, NULL))
+ |FROM t""".stripMargin,
+ """SELECT
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 10),
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 20)
+ |FROM t""".stripMargin)
+ }
+ }
+
+ test("rewrite with all NULLs in conditional branch") {
+ withTempView("t") {
+ spark.range(3)
+ .selectExpr(
+ "cast(id % 2 + 1 as int) as key",
+ "cast(id * 5 as int) as col1",
+ "cast(id * 100 as int) as col2")
+ .createOrReplaceTempView("t")
+
+ // col1 values are 0, 5, 10 - both thresholds (> 10 and > 20) yield zero matches,
+ // so both counts return 0. Two counts so the rewrite fires.
+ checkRewriteAndResult(
+ """SELECT key,
+ | COUNT(DISTINCT IF(col1 > 10, col2, NULL)),
+ | COUNT(DISTINCT IF(col1 > 20, col2, NULL))
+ |FROM t GROUP BY key""".stripMargin,
+ """SELECT key,
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 10),
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 20)
+ |FROM t GROUP BY key""".stripMargin)
+ }
+ }
+
+ test("rewrite with duplicates in base column") {
+ withTempView("t") {
+ spark.range(6)
+ .selectExpr(
+ "cast(id % 2 + 1 as int) as key",
+ "cast(id * 10 as int) as col1",
+ "case when id % 3 = 0 then 100 when id % 3 = 1 then 100 else 200 end as col2")
+ .createOrReplaceTempView("t")
+
+ // Two counts on the same base (with duplicates) so the rewrite fires.
+ checkRewriteAndResult(
+ """SELECT key,
+ | COUNT(DISTINCT IF(col1 > 10, col2, NULL)),
+ | COUNT(DISTINCT IF(col1 > 20, col2, NULL))
+ |FROM t GROUP BY key""".stripMargin,
+ """SELECT key,
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 10),
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 20)
+ |FROM t GROUP BY key""".stripMargin)
+ }
+ }
+
+ test("different bases skip the conditional rewrite and keep correct results") {
+ withTempView("t") {
+ spark.range(5)
+ .selectExpr(
+ "cast(id % 2 + 1 as int) as key",
+ "cast(id * 10 as int) as col1",
+ "case when id % 3 = 0 then null else cast(id * 100 as int) end as col2",
+ "case when id % 4 = 0 then null else cast(id * 10 as string) end as col3")
+ .createOrReplaceTempView("t")
+
+ val conditionalSql =
+ """SELECT key,
+ | COUNT(DISTINCT IF(col1 > 10, col2, NULL)) as cnt1,
+ | COUNT(DISTINCT IF(col1 > 5, col3, NULL)) as cnt2
+ |FROM t GROUP BY key""".stripMargin
+
+ val filterSql =
+ """SELECT key,
+ | COUNT(DISTINCT col2) FILTER (WHERE col1 > 10) as cnt1,
+ | COUNT(DISTINCT col3) FILTER (WHERE col1 > 5) as cnt2
+ |FROM t GROUP BY key""".stripMargin
+
+ checkRewriteAndResult(conditionalSql, filterSql)
+
+ // col2 and col3 are different distinct children, so normalization does not
+ // reduce the group count and the gate keeps the original IFs.
+ withSQLConf(SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "true") {
+ val plan = spark.sql(conditionalSql).queryExecution.optimizedPlan
+ assert(!hasUserConditionFilter(plan),
+ "different bases should not produce a user-condition FILTER clause")
+ }
+ }
+ }
+
+ test("rewrite does not affect COUNT(DISTINCT IF(cond, col, non_null))") {
+ withTempView("t") {
+ spark.range(3)
+ .selectExpr(
+ "cast(id % 2 + 1 as int) as key",
+ "cast(id * 10 as int) as col1",
+ "cast(id * 100 as int) as col2")
+ .createOrReplaceTempView("t")
+
+ // Two counts so mayNeedtoRewrite fires and the non-null-else guard is exercised.
+ val sqlText =
+ """SELECT key,
+ | COUNT(DISTINCT IF(col1 > 10, col2, 0)),
+ | COUNT(DISTINCT IF(col1 > 20, col2, 0))
+ |FROM t GROUP BY key""".stripMargin
+
+ // Collect the conf-off result as the semantic baseline; the conf-on query must match it.
+ val withoutRewriteRows = withSQLConf(
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "false") {
+ spark.sql(sqlText).collect()
+ }
+ withSQLConf(
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "true") {
+ checkAnswer(spark.sql(sqlText), withoutRewriteRows)
+ }
+
+ // When the switch is enabled, the non-null ELSE branch must not be canonicalized
+ // into a user-condition FILTER; only the internal gid-routing filters introduced
+ // by the Expand rewrite may be present.
+ val hasFilter = withSQLConf(
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "true") {
+ hasUserConditionFilter(spark.sql(sqlText).queryExecution.optimizedPlan)
+ }
+ assert(!hasFilter,
+ "Non-null ELSE branch should not produce a user-condition FILTER clause")
+ }
+ }
+
+ test("rewrite is not applied to error-prone base expressions (ANSI divide by zero)") {
+ withTempView("t") {
+ // Rows with x = 0 make both conditions false, so the IF branches short-circuit
+ // and 10 / x is never evaluated for them.
+ spark.range(5)
+ .selectExpr(
+ "cast(id % 2 + 1 as int) as key",
+ "cast(id % 2 as int) as x")
+ .createOrReplaceTempView("t")
+
+ // Two conditional distinct counts on the same error-prone base so that rewrite()
+ // is reached; the canonicalization must NOT fire for such a base.
+ val sqlText =
+ """SELECT key,
+ | COUNT(DISTINCT IF(x <> 0, 10 / x, NULL)),
+ | COUNT(DISTINCT IF(x > 0, 10 / x, NULL))
+ |FROM t GROUP BY key""".stripMargin
+
+ withSQLConf(
+ SQLConf.ANSI_ENABLED.key -> "true",
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "true") {
+ // Must not raise DIVIDE_BY_ZERO: the canonicalization must leave the IFs intact
+ // so that their branch short-circuiting is preserved.
+ checkAnswer(spark.sql(sqlText), Seq(Row(1, 0L, 0L), Row(2, 1L, 1L)))
+ assert(!hasUserConditionFilter(spark.sql(sqlText).queryExecution.optimizedPlan),
+ "error-prone base should not produce a user-condition FILTER clause")
+ }
+ }
+ }
+
+ test("guard: high-cardinality base with low-selectivity disjoint predicates") {
+ withTempView("t") {
+ // ord is unique (high-cardinality base); each predicate matches ~1% of rows and
+ // they are disjoint. This is the workload shape that regressed before the
+ // union-of-filters guard: the guarded key must stay bounded by the pre-rewrite
+ // plan's cardinality while the Expand stays collapsed.
+ spark.range(1000)
+ .selectExpr(
+ "cast(id % 7 as int) as key",
+ "cast(id as bigint) as ord",
+ "cast(id % 100 as int) as bucket")
+ .createOrReplaceTempView("t")
+
+ checkRewriteAndResult(
+ """SELECT key,
+ | COUNT(DISTINCT IF(bucket = 0, ord, NULL)),
+ | COUNT(DISTINCT IF(bucket = 3, ord, NULL))
+ |FROM t GROUP BY key""".stripMargin,
+ """SELECT key,
+ | COUNT(DISTINCT ord) FILTER (WHERE bucket = 0),
+ | COUNT(DISTINCT ord) FILTER (WHERE bucket = 3)
+ |FROM t GROUP BY key""".stripMargin)
+ }
+ }
+
+ test("guard: mixed overlapping windows and disjoint flags") {
+ withTempView("t") {
+ spark.range(1000)
+ .selectExpr(
+ "cast(id % 7 as int) as key",
+ "cast(id as bigint) as ord",
+ "cast(id % 30 as int) as day",
+ "cast(id % 100 as int) as bucket")
+ .createOrReplaceTempView("t")
+
+ // Overlapping windows (day < 10 is a subset of day < 30) plus disjoint selective flags in
+ // the same query: the union guard must keep every count correct.
+ checkRewriteAndResult(
+ """SELECT key,
+ | COUNT(DISTINCT IF(day < 10, ord, NULL)),
+ | COUNT(DISTINCT IF(day < 30, ord, NULL)),
+ | COUNT(DISTINCT IF(bucket = 0, ord, NULL)),
+ | COUNT(DISTINCT IF(bucket = 7, ord, NULL))
+ |FROM t GROUP BY key""".stripMargin,
+ """SELECT key,
+ | COUNT(DISTINCT ord) FILTER (WHERE day < 10),
+ | COUNT(DISTINCT ord) FILTER (WHERE day < 30),
+ | COUNT(DISTINCT ord) FILTER (WHERE bucket = 0),
+ | COUNT(DISTINCT ord) FILTER (WHERE bucket = 7)
+ |FROM t GROUP BY key""".stripMargin)
+ }
+ }
+
+ test("guard: nullable condition that is NULL for some rows") {
+ withTempView("t") {
+ // Literal IF(NULL, ...) is folded to CAST(NULL AS ...) by SimplifyConditionals
+ // before Distinct Aggregate Rewrite, so it never reaches the union guard. A
+ // predicate over a nullable column that is NULL for some rows does.
+ spark.range(50)
+ .selectExpr(
+ "cast(id % 7 as int) as key",
+ "cast(id as bigint) as ord",
+ "cast(id % 100 as int) as bucket",
+ "case when id % 3 = 0 then cast(null as int) else cast(id % 5 as int) end as flag")
+ .createOrReplaceTempView("t")
+
+ val sqlText =
+ """SELECT key,
+ | COUNT(DISTINCT IF(flag > 0, ord, NULL)),
+ | COUNT(DISTINCT IF(bucket = 0, ord, NULL))
+ |FROM t GROUP BY key""".stripMargin
+ val withoutRewriteRows = withSQLConf(
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "false") {
+ spark.sql(sqlText).collect()
+ }
+ withSQLConf(
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "true") {
+ checkAnswer(spark.sql(sqlText), withoutRewriteRows)
+
+ val plan = spark.sql(sqlText).queryExecution.optimizedPlan
+ val expand = plan.collectFirst { case e: Expand => e }.getOrElse(
+ fail(s"expected Expand in optimized plan:\n$plan"))
+ assert(expand.projections.size == 1,
+ s"expected 1 distinct group, got ${expand.projections.size}")
+ val guard = expand.projections.head.collectFirst {
+ case i @ If(_, trueValue, falseValue)
+ if falseValue.foldable && falseValue.eval() == null &&
+ trueValue.references.exists(_.name == "ord") => i
+ }.getOrElse(fail(s"no union guard over ord in Expand:\n$plan"))
+ val leaves = orLeaves(guard.predicate)
+ assert(leaves.exists(_.references.exists(_.name == "flag")),
+ s"guard misses flag predicate: ${guard.predicate}")
+ assert(leaves.exists(_.references.exists(_.name == "bucket")),
+ s"guard misses bucket predicate: ${guard.predicate}")
+ }
+ }
+ }
+
+ test("guard: mixed filtered and unfiltered counts on the same base") {
+ withTempView("t") {
+ spark.range(1000)
+ .selectExpr(
+ "cast(id % 7 as int) as key",
+ "cast(id as bigint) as ord",
+ "cast(id % 100 as int) as bucket")
+ .createOrReplaceTempView("t")
+
+ // The unfiltered count needs ord over ALL rows, so the shared Expand key must
+ // stay unguarded; the filtered counts ride along via their flag columns.
+ checkRewriteAndResult(
+ """SELECT key,
+ | COUNT(DISTINCT ord),
+ | COUNT(DISTINCT IF(bucket = 0, ord, NULL))
+ |FROM t GROUP BY key""".stripMargin,
+ """SELECT key,
+ | COUNT(DISTINCT ord),
+ | COUNT(DISTINCT ord) FILTER (WHERE bucket = 0)
+ |FROM t GROUP BY key""".stripMargin)
+ }
+ }
+
+ test("rewrite is present in optimized plan") {
+ withTempView("t") {
+ spark.range(2)
+ .selectExpr(
+ "cast(id + 1 as int) as key",
+ "cast(id * 10 as int) as col1",
+ "cast(id * 100 as int) as col2")
+ .createOrReplaceTempView("t")
+
+ // Two conditional distinct counts on the same base column trigger canonicalization,
+ // so the optimized plan must contain user-condition FILTER clauses.
+ val hasFilter = withSQLConf(
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key -> "true") {
+ val df = spark.sql(
+ """SELECT key,
+ | COUNT(DISTINCT IF(col1 > 10, col2, NULL)) as cnt1,
+ | COUNT(DISTINCT IF(col1 > 5, col2, NULL)) as cnt2
+ |FROM t GROUP BY key""".stripMargin)
+ hasUserConditionFilter(df.queryExecution.optimizedPlan)
+ }
+
+ assert(hasFilter, "Optimized plan should contain user-condition FILTER clause")
+ }
+ }
+
+ private def servingLogFixture(f: => Unit): Unit = {
+ withTempView("serving_log", "models") {
+ spark.range(20).selectExpr(
+ "id % 3 as key",
+ "id as request_id",
+ "case when id % 11 = 0 then null else id % 5 end as user_id",
+ "id % 4 as model",
+ "id % 3 as tier",
+ "id % 7 as priority",
+ "id * 10 as tokens").createOrReplaceTempView("serving_log")
+ spark.range(2).selectExpr(
+ "id as model",
+ "id % 2 as tier").createOrReplaceTempView("models")
+ f
+ }
+ }
+
+ test("guard: EXISTS, IN, and NOT IN filters are not joined twice") {
+ servingLogFixture {
+ // Another distinct aggregate forces the Expand path. Each predicate subquery
+ // is its own filtered group; guarding it would join the dimension table twice.
+ val sqlText =
+ """SELECT key,
+ | SUM(DISTINCT tokens),
+ | COUNT(DISTINCT request_id) FILTER (WHERE EXISTS (
+ | SELECT 1 FROM models WHERE serving_log.model = models.model)),
+ | COUNT(DISTINCT user_id) FILTER (WHERE tier IN (
+ | SELECT tier FROM models WHERE models.model = serving_log.model)),
+ | COUNT(DISTINCT priority) FILTER (WHERE user_id NOT IN (
+ | SELECT tier FROM models WHERE models.model = serving_log.model))
+ |FROM serving_log GROUP BY key""".stripMargin
+ assertSameExistenceJoinCount(sqlText, expectedJoins = 3)
+ }
+ }
+
+ test("guard: IF and CASE conditions with predicate subqueries stay un-normalized") {
+ servingLogFixture {
+ // Same base, so a subquery-blind normalize would collapse these into one group.
+ // That group cannot be guarded, and Expand would project the raw request_id.
+ val sqlText =
+ """SELECT key,
+ | COUNT(DISTINCT IF(EXISTS (
+ | SELECT 1 FROM models WHERE serving_log.model = models.model),
+ | request_id, NULL)),
+ | COUNT(DISTINCT CASE WHEN tier IN (
+ | SELECT tier FROM models WHERE models.model = serving_log.model)
+ | THEN request_id END),
+ | COUNT(DISTINCT CASE WHEN user_id NOT IN (
+ | SELECT tier FROM models WHERE models.model = serving_log.model)
+ | THEN request_id ELSE NULL END)
+ |FROM serving_log GROUP BY key""".stripMargin
+ assertSameExistenceJoinCount(sqlText, expectedJoins = 3, stayUnnormalized = true)
+ }
+ }
+}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
index 1e98eaf7bb68..1a17dd700c5f 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
@@ -1685,10 +1685,12 @@ class WholeStageCodegenSuite extends SharedSparkSession
test("Expand should eliminate common subexpressions across branches") {
// The conditions of the two conditional COUNT DISTINCT aggregates share `sinh(v)`, which
- // `RewriteDistinctAggregates` places in different branches of the Expand. Since all the
- // branches of an Expand consume the same input row, with subexpression elimination
- // `sinh(v)` should be evaluated once per input row (before the branch loop) instead of
- // once per branch.
+ // `RewriteDistinctAggregates` places in different branches of the Expand. The bases
+ // differ (`k` vs `v`), so the conditional rewrite does not reduce the distinct-group
+ // count and is not applied. Each branch stays the original IF and evaluates `sinh(v)`
+ // once. Since all the branches consume the same input row, with subexpression
+ // elimination `sinh(v)` should be evaluated once per input row (before the branch
+ // loop) instead of once per branch.
def runQuery(): String = {
val df = spark.range(10)
.selectExpr("id as k", "cast(id as double) as v")
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/ExpandBenchmark.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/ExpandBenchmark.scala
index 586dfec19620..ff56afebee05 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/ExpandBenchmark.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/ExpandBenchmark.scala
@@ -33,9 +33,10 @@ import org.apache.spark.sql.internal.SQLConf
* OptimizeExpand rule that pre-aggregates data before the Expand. Controlled by
* spark.sql.optimizer.optimizeExpandRatio (default -1 = disabled).
*
- * It also measures subexpression elimination in Expand: conditional-aggregate
- * queries whose conditions all share the same expensive subexpression, which
- * ends up in every branch of the Expand. Controlled by
+ * It also measures subexpression elimination in Expand. With the conditional
+ * distinct rewrite on (the default), the shared datetime expression is repeated
+ * in both Expand branches: the distinct branch for the counts and the regular
+ * branch for the sums. Controlled by
* spark.sql.subexpressionElimination.enabled (default true).
*
* To run this benchmark:
@@ -50,6 +51,8 @@ object ExpandBenchmark extends SqlBasedBenchmark {
private val OPTIMIZE_EXPAND_RATIO =
SQLConf.OPTIMIZE_EXPAND_RATIO.key
+ private val REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED =
+ SQLConf.REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED.key
private def prepareTable(name: String, N: Long,
keyMod: Int, colMods: Seq[Int]): Unit = {
@@ -127,12 +130,15 @@ object ExpandBenchmark extends SqlBasedBenchmark {
/**
* Prepares a traffic-like fact table: one row per page view, with a user id,
* a date-string partition column `pt` (format `yyyyMMdd`), and a metric value.
+ * `pt` starts at 2023-06-02 and spans 730 days, so against the 2025-06-01
+ * anchor in [[conditionalAggsQuery]] `daysSince` is 1 through 730 and the
+ * widest window matches every row.
*/
private def prepareTrafficTable(name: String, N: Long, userMod: Int): Unit = {
spark.range(N)
.selectExpr(
s"cast(id % $userMod as bigint) as user_id",
- "date_format(date_add(date '2023-06-01', cast(id % 730 as int)), 'yyyyMMdd') as pt",
+ "date_format(date_add(date '2023-06-02', cast(id % 730 as int)), 'yyyyMMdd') as pt",
"cast(id % 3600 as bigint) as value")
.createOrReplaceTempView(name)
}
@@ -142,9 +148,10 @@ object ExpandBenchmark extends SqlBasedBenchmark {
* given day windows, one conditional COUNT(DISTINCT) and one conditional SUM
* whose conditions all share the same expensive datetime subexpression
* (parse `pt`, format it back, then `datediff` against a fixed date).
- * `RewriteDistinctAggregates` places those conditions in the branches of an
- * Expand, so the shared subexpression is codegen'd once per branch without
- * subexpression elimination.
+ * With the conditional distinct rewrite on, the counts share one distinct
+ * Expand branch and the sums stay on the regular branch, so the shared
+ * subexpression is repeated in both. With the rewrite off, each count keeps
+ * its own distinct branch.
*/
private def conditionalAggsQuery(table: String, windows: Seq[Int]): String = {
val daysSince = "datediff(" +
@@ -161,12 +168,38 @@ object ExpandBenchmark extends SqlBasedBenchmark {
|GROUP BY user_id""".stripMargin
}
+ /**
+ * The traffic query's day windows are nested (day <= 1 is a subset of day <= 7, ... of
+ * day <= 730) and together cover every row, so every row matches some predicate and the
+ * union-of-filters guard degenerates to the raw base. This is the best case for the
+ * conditional-count collapse itself: conf on collapses the 9 conditional counts into one
+ * distinct group, removing most of the Expand fan-out.
+ */
+ private def overlappingWorkloadBenchmark(
+ title: String, N: Long, table: String): Unit = {
+ val benchmark = new Benchmark(title, N, output = output)
+ val sql = conditionalAggsQuery(table, Seq(1, 7, 14, 30, 60, 90, 180, 365, 730))
+
+ benchmark.addCase("conf off (9 distinct groups)", numIters = 3) { _ =>
+ withSQLConf(REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED -> "false") {
+ spark.sql(sql).noop()
+ }
+ }
+ benchmark.addCase("conf on (1 collapsed group)", numIters = 3) { _ =>
+ withSQLConf(REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED -> "true") {
+ spark.sql(sql).noop()
+ }
+ }
+
+ benchmark.run()
+ }
+
private def subExprEliminationBenchmark(
title: String, N: Long, table: String): Unit = {
val benchmark = new Benchmark(title, N, output = output)
val sql = conditionalAggsQuery(table, Seq(1, 7, 14, 30, 60, 90, 180, 365, 730))
- benchmark.addCase("CSE disabled (re-evaluate per branch)", numIters = 3) { _ =>
+ benchmark.addCase("CSE disabled (re-evaluate each use)", numIters = 3) { _ =>
withSQLConf(SQLConf.SUBEXPRESSION_ELIMINATION_ENABLED.key -> "false") {
spark.sql(sql).noop()
}
@@ -180,6 +213,53 @@ object ExpandBenchmark extends SqlBasedBenchmark {
benchmark.run()
}
+ /**
+ * Prepares a table with a unique base column `ord`, a grouping key `user_id`, and
+ * a 100-value flag column `bucket`. This is the workload shape that regressed in
+ * SPARK-56898 before the union-of-filters guard: high-cardinality base with
+ * low-selectivity disjoint predicates. Unguarded, collapsing the conditional counts
+ * keys the first aggregate by every distinct base value (unbounded by how few rows
+ * the predicates select); guarded, rows matching no predicate collapse into a NULL
+ * key, matching the pre-rewrite plan's cardinality while keeping the collapsed
+ * Expand.
+ */
+ private def prepareHostileTable(name: String, N: Long, userMod: Int): Unit = {
+ spark.range(N)
+ .selectExpr(
+ s"cast(id % $userMod as bigint) as user_id",
+ "cast(id as bigint) as ord",
+ "cast(id % 100 as int) as bucket")
+ .createOrReplaceTempView(name)
+ }
+
+ private def conditionalCountsQuery(table: String, numFlags: Int): String = {
+ val counts = (0 until numFlags).map(i =>
+ s"count(distinct if(bucket = $i, ord, null)) as flag_cnt_$i").mkString(",\n ")
+ s"""SELECT user_id,
+ | $counts
+ |FROM $table
+ |GROUP BY user_id""".stripMargin
+ }
+
+ private def hostileWorkloadBenchmark(
+ title: String, N: Long, table: String): Unit = {
+ val benchmark = new Benchmark(title, N, output = output)
+ val sql = conditionalCountsQuery(table, numFlags = 10)
+
+ benchmark.addCase("conf off (10 distinct groups)", numIters = 3) { _ =>
+ withSQLConf(REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED -> "false") {
+ spark.sql(sql).noop()
+ }
+ }
+ benchmark.addCase("conf on (1 guarded group)", numIters = 3) { _ =>
+ withSQLConf(REWRITE_COUNT_DISTINCT_CONDITIONAL_ENABLED -> "true") {
+ spark.sql(sql).noop()
+ }
+ }
+
+ benchmark.run()
+ }
+
override def runBenchmarkSuite(mainArgs: Array[String]): Unit = {
val N = 10L << 20 // ~10M rows
@@ -281,5 +361,26 @@ object ExpandBenchmark extends SqlBasedBenchmark {
"9 conditional COUNT(DISTINCT) + 9 conditional SUM sharing one subexpression",
numRows, "expand_traffic")
}
+
+ runBenchmark("Expand: conditional COUNT(DISTINCT), overlapping predicates") {
+ val numRows = 5L << 20 // ~5M rows
+ prepareTrafficTable("expand_traffic_windows", numRows, userMod = 1000000)
+ overlappingWorkloadBenchmark(
+ "9 conditional COUNT(DISTINCT) + 9 conditional SUM, overlapping day windows",
+ numRows, "expand_traffic_windows")
+ }
+
+ runBenchmark("Expand: conditional COUNT(DISTINCT), high-cardinality base") {
+ // ~10M rows, 100K groups (~100 rows each), unique base column. Each of the 10
+ // disjoint predicates matches ~1% of rows. Conf-off keeps 10 distinct groups
+ // with NULL-collapsed keys; conf-on collapses to 1 guarded group, whose key
+ // cardinality must not regress against the conf-off plan.
+ val hostileRows = 10L << 20
+ prepareHostileTable("expand_hostile", hostileRows, userMod = 100000)
+ hostileWorkloadBenchmark(
+ "10 conditional COUNT(DISTINCT), unique base, " +
+ "1%-selective disjoint predicates",
+ hostileRows, "expand_hostile")
+ }
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org