xiliang678 opened a new pull request, #60573:
URL: https://github.com/apache/spark/pull/60573

   ### What changes were proposed in this pull request?
   
   SPARK-56898 (fix version 4.4.0, not released yet) made 
`RewriteDistinctAggregates` normalize `COUNT(DISTINCT IF(cond, base, NULL))` 
and `COUNT(DISTINCT CASE WHEN cond THEN base END)` to `COUNT(DISTINCT base) 
FILTER (WHERE cond)` while 
`spark.sql.optimizer.rewriteCountDistinctConditional.enabled` is true, which is 
its default. Several such counts over one base then share one group of the 
`Expand` that the rule builds. The rule also guards that group's distinct key, 
the value that the `Expand` projects for it, with the union of the counts' 
filters: `IF(cond_1 OR ... OR cond_n, base, NULL)` (the union-of-filters 
guard). Rows that match no filter then project NULL.
   
   For each value of the GROUP BY keys, the first aggregate above the `Expand` 
then outputs, for that group, one row per distinct base value among the rows 
that match some condition, plus at most one NULL row. Without the 
normalization, it outputs no fewer: for each condition, one row per distinct 
base value among the rows that match that condition, plus at most one NULL row.
   
   This PR fixes two cases where the rule normalized counts and then built 
their group without the guard, which left the base itself as the group's 
distinct key on every row:
   
   1. **Non-deterministic condition.** `extractCondAndBase`, which decides 
which counts to normalize, now also requires the condition to be deterministic. 
Before, such a count was normalized and joined the group of the other counts 
over its base. The guard applies only when every filter of a group is 
deterministic, so then no count of that group was guarded. Now the count keeps 
its own group, whose distinct key is its original `IF` or `CASE WHEN`, and the 
other counts over the base can still share a guarded group. The base was 
already required to be deterministic: it must pass 
`ExprUtils.canEvaluateUnconditionally`, which requires a deterministic 
expression.
   2. **Config read twice.** For one `Aggregate`, 
`normalizeCountDistinctConditional` read 
`spark.sql.optimizer.rewriteCountDistinctConditional.enabled`, and the rule's 
`rewrite` method read it again for the guard. Now `rewrite` reads it once and 
uses that value for both, and `normalizeCountDistinctConditional` no longer 
reads it. The existing check in `rewrite` that keeps the normalized form only 
when it has fewer distinct groups than the original moves into a new helper, 
`normalizedWithFewerGroups`. The helper calls 
`normalizeCountDistinctConditional`, and `rewrite` calls the helper only when 
the config is on.
   
   It also updates the docs of the config, of 
`normalizeCountDistinctConditional` and of `extractCondAndBase`. And it sets 
the config to true in the subexpression elimination benchmark of 
`ExpandBenchmark`, which compares two settings of subexpression elimination on 
the normalized plan, so that it measures that plan whatever the default. The 
file's two other benchmarks of this rewrite already set the config in each of 
their cases.
   
   ### Why are the changes needed?
   
   Without the guard, the first aggregate above the `Expand` outputs, for each 
value of the GROUP BY keys, one row per distinct base value of all rows, not 
only of the rows that match a condition. Results stay correct, because the 
FILTER clauses still select the rows of each count, but for a base with many 
distinct values that output can be much larger: 10000 rows instead of 207 in 
the row-count test below.
   
   - Case 1: analysis rejects non-deterministic expressions in aggregate 
arguments, and `CollapseProject` inlines only deterministic expressions, so we 
know of no query that reaches this case. With the new check, the guard no 
longer depends on that.
   - Case 2: the optimizer reads the session's `SQLConf`, so another thread 
that sets the config on the same session can change it while the rule runs. 
Many rules read the config more than once, but here the two reads decide two 
halves of one rewrite. If the config is turned off between them, the rule keeps 
the normalized counts and skips their guard. Reading it once avoids that.
   
   ### Does this PR introduce _any_ user-facing change?
   
   No. Results do not change. Plans change only in the two cases above: a 
non-deterministic condition reaching the rule, which we know of no query to 
produce, and the config changing while the rule runs.
   
   ### How was this patch tested?
   
   New tests, added in a commit before the change:
   - `RewriteDistinctAggregatesSuite`, "do not normalize counts whose condition 
is non-deterministic" (IF and CASE WHEN forms): a plan built directly, since 
analysis would reject it, with a non-deterministic count next to two 
deterministic counts over the same base. Before the change, both forms failed: 
the three counts shared one group, whose distinct key was the base itself.
   - `RewriteDistinctAggregatesSuite`, "the rule reads the config once per 
aggregate": a condition whose `deterministic` turns the config off the first 
time it is called. Before the change, that first call came after the rule had 
read the config for the normalization and before it read it for the guard, so 
the test failed: the normalized counts' group had no guard.
   - `RewriteDistinctAggregatesSuite`, "do not normalize COUNT(DISTINCT 
IF(...), col)": a count with a second argument is not normalized. It covers an 
existing check, and passed before the change.
   - `RewriteDistinctAggregatesConditionalQuerySuite`, "the aggregate above the 
Expand outputs no more rows than with the config off": 10000 rows with a unique 
base and a GROUP BY key with 7 values, and two conditional counts whose 
conditions each match 100 rows, never the same row. The first aggregate above 
the `Expand` outputs 214 rows with the config off (2 * (100 + 7)), 207 with it 
on (200 + 7), and 10000 when the guard is removed by hand from the same plan, 
which is the plan that case 2 produces for this query. It passed before the 
change.
   - `RewriteDistinctAggregatesConditionalQuerySuite`, "conditions on a column 
computed by a non-deterministic expression keep the guard": three conditional 
counts over one base, one of whose conditions reads a column that a subquery in 
the FROM clause computes with `input_file_name()`. The test checks that the new 
check does not reject that condition, which is deterministic, and that the 
three counts share one guarded group. It passed before and after the change.
   
   With the change, these pass locally: all 42 tests of 
`RewriteDistinctAggregatesSuite` and all 19 of 
`RewriteDistinctAggregatesConditionalQuerySuite`, and two other suites with 
tests of this rule, `DataFrameAggregateSuite` (218 tests) and 
`WholeStageCodegenSuite` (117 tests, plus 3 that are ignored, as on master). 
Scalastyle finds no errors in `catalyst` and `sql`, main and test.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Claude Code (Claude Opus 5.5)
   
   This pull request and its description were written by Isaac.
   


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