kosiew commented on code in PR #27080:
URL: https://github.com/apache/datafusion/pull/27080#discussion_r4741042049


##########
datafusion/optimizer/src/single_distinct_to_groupby.rs:
##########
@@ -118,6 +120,13 @@ fn is_single_distinct_agg(
     let mut distinct_aggs = vec![];
     let mut has_count_rollup = false;
     for expr in aggr_expr {
+        // Peel aliases on the aggregate itself. The DataFrame API puts them 
there
+        // (e.g. `count(col("b")).distinct().alias("n")`), and so do rewrites 
that
+        // have to preserve an aggregate's output name.
+        let mut expr = expr;
+        while let Expr::Alias(alias) = expr {

Review Comment:
   Grouping columns named `alias1` or `count(alias1)` now cause valid aliased 
DataFrame queries to fail. Please ensure collision-free names in both stages or 
skip the rewrite on detected collisions without swallowing unrelated errors. 
Add DataFrame regressions asserting output names and results.



##########
datafusion/optimizer/src/single_distinct_to_groupby.rs:
##########
@@ -371,12 +382,22 @@ impl OptimizerRule for SingleDistinctToGroupBy {
                                 Ok((outer, proj))
                             }
                         }
-                        _ => Ok((aggr_expr.clone(), aggr_expr)),
+                        other => Ok((other.clone(), other)),
                     })
                     .collect::<Result<Vec<_>>>()?
                     .into_iter()
                     .unzip();
 
+                // With their aliases stripped, aggregates that differed only 
in
+                // their alias are the same expression, and an `Aggregate` 
cannot
+                // output a name twice. Compute each one once: the projection
+                // below still selects it under every original name.
+                let mut unique_outer_aggr_exprs = IndexSet::new();

Review Comment:
   Optional: insert each rewritten producer into the `IndexSet` as it is built 
and retain `(projection_expr, producer_slot)` together. This avoids temporary 
parallel vectors while preserving first-seen producer order.



##########
datafusion/core/tests/dataframe/mod.rs:
##########
@@ -838,6 +838,84 @@ async fn aggregate_assert_no_empty_batches() -> Result<()> 
{
     Ok(())
 }
 
+// The DataFrame API puts an alias on the aggregate itself, where SQL leaves 
the
+// aggregate bare and aliases it in a projection. Both have to reach the same 
plan.
+#[tokio::test]
+async fn aliased_single_distinct_aggregate_is_rewritten() -> Result<()> {
+    let ctx = SessionContext::new();
+    let df = ctx
+        .read_batch(record_batch!(
+            ("a", Int32, [1, 1, 2, 2]),
+            ("b", Int32, [1, 1, 1, 2])
+        )?)?
+        .aggregate(vec![col("a")], vec![count_distinct(col("b")).alias("n")])?;
+
+    assert_snapshot!(df.clone().into_optimized_plan()?, @r"
+    Projection: ?table?.a, count(alias1) AS n
+      Aggregate: groupBy=[[?table?.a]], aggr=[[count(alias1)]]
+        Aggregate: groupBy=[[?table?.a, ?table?.b AS alias1]], aggr=[[]]
+          TableScan: ?table? projection=[a, b]
+    ");
+
+    assert_batches_eq!(
+        &[
+            "+---+---+",
+            "| a | n |",
+            "+---+---+",
+            "| 1 | 1 |",
+            "| 2 | 2 |",
+            "+---+---+",
+        ],
+        &df.sort_by(vec![col("a")])?.collect().await?
+    );
+
+    Ok(())
+}
+
+/// Stripping the aliases leaves two identical aggregates, which an `Aggregate`
+/// can't output together. They must share one, as the SQL planner's do. The
+/// `sum` follows them so its position in the outer aggregate differs from its
+/// position in the original one; `b` is `Int64` so that `sum` needs no cast,
+/// which would count as a second distinct field and skip the rewrite.
+#[tokio::test]
+async fn identical_aliased_single_distinct_aggregates_are_computed_once() -> 
Result<()> {
+    let ctx = SessionContext::new();
+    let df = ctx
+        .read_batch(record_batch!(
+            ("a", Int32, [1, 1, 2, 2]),
+            ("b", Int64, [1, 1, 1, 2])
+        )?)?
+        .aggregate(
+            vec![col("a")],
+            vec![
+                count_distinct(col("b")).alias("n1"),
+                count_distinct(col("b")).alias("n2"),
+                sum_distinct(col("b")).alias("s"),
+            ],
+        )?;
+
+    assert_snapshot!(df.clone().into_optimized_plan()?, @r"
+    Projection: ?table?.a, count(alias1) AS n1, count(alias1) AS n2, 
sum(alias1) AS s
+      Aggregate: groupBy=[[?table?.a]], aggr=[[count(alias1), sum(alias1)]]
+        Aggregate: groupBy=[[?table?.a, ?table?.b AS alias1]], aggr=[[]]
+          TableScan: ?table? projection=[a, b]
+    ");
+
+    assert_batches_eq!(
+        &[
+            "+---+----+----+---+",
+            "| a | n1 | n2 | s |",
+            "+---+----+----+---+",
+            "| 1 | 1  | 1  | 1 |",
+            "| 2 | 2  | 2  | 3 |",
+            "+---+----+----+---+",
+        ],
+        &df.sort_by(vec![col("a")])?.collect().await?
+    );
+

Review Comment:
   Optional: assign different field metadata to the two count aliases and 
assert both survive collection while sharing one producer. This would guard 
against future metadata regressions.



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