saadtajwar commented on code in PR #23682:
URL: https://github.com/apache/datafusion/pull/23682#discussion_r3640816894


##########
datafusion/optimizer/src/coalesce_first_last.rs:
##########
@@ -0,0 +1,658 @@
+// 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.
+
+//! [`CoalesceFirstLast`] coalesces peer `first_value` / `last_value` aggregate
+//! expressions that share the same `ORDER BY` key into a single struct-valued
+//! aggregate.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::optimizer::ApplyOrder;
+use crate::{OptimizerConfig, OptimizerRule};
+
+use datafusion_common::Result;
+use datafusion_common::tree_node::Transformed;
+use datafusion_expr::expr::{
+    AggregateFunction, AggregateFunctionParams, NullTreatment, Sort,
+};
+use datafusion_expr::{
+    Aggregate, AggregateUDF, Expr, LogicalPlan, LogicalPlanBuilder, col, lit,
+};
+
+use indexmap::IndexMap;
+
+const FIRST_VALUE: &str = "first_value";
+const LAST_VALUE: &str = "last_value";
+const NAMED_STRUCT: &str = "named_struct";
+const GET_FIELD: &str = "get_field";
+
+/// Coalesces peer `first_value` / `last_value` aggregates that share one
+/// `ORDER BY` key into a single struct-valued aggregate, with a projection on
+/// top to unpack the struct back into the original columns:
+///
+/// ```text
+/// Aggregate: groupBy=[[p]], aggr=[[first_value(a ORDER BY o DESC),
+///                                  first_value(b ORDER BY o DESC)]]
+/// ```
+///
+/// becomes
+///
+/// ```text
+/// Projection: p, get_field(wrapped, 'c0'), get_field(wrapped, 'c1')
+///   Aggregate: groupBy=[[p]],
+///              aggr=[[first_value(named_struct('c0', a, 'c1', b) ORDER BY o 
DESC) AS wrapped]]
+/// ```
+///
+/// The input is scanned once, not once per expression, and holds one per-group
+/// state slot instead of N.
+///
+/// Off by default (`optimizer.enable_coalesce_first_last`); no-ops if
+/// `named_struct` / `get_field` are not registered.
+#[derive(Default, Debug)]
+pub struct CoalesceFirstLast {}
+
+impl CoalesceFirstLast {
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+/// `(function name, ORDER BY key, null treatment)` — peers may be coalesced 
only
+/// when all three match.
+// Peers are bucketed by (function name, ORDER BY, null treatment). Using the
+// function *name* is safe because a session resolves one canonical UDF per
+// name, so same-keyed members share an implementation.
+type BucketKey = (String, Vec<Sort>, Option<NullTreatment>);
+
+struct Coalesceable {
+    key: BucketKey,
+    func: Arc<AggregateUDF>,
+    value: Expr,
+}
+
+fn classify(expr: &Expr) -> Option<Coalesceable> {
+    // `Aggregate::aggr_expr` entries are documented to be either an
+    // `AggregateFunction` or an `Alias` wrapping one (e.g. built via the
+    // DataFrame API); unwrap the alias so aliased peers are coalesced too.
+    let inner = match expr {
+        Expr::Alias(alias) => alias.expr.as_ref(),
+        other => other,
+    };
+    let Expr::AggregateFunction(AggregateFunction { func, params }) = inner 
else {
+        return None;
+    };
+    let name = func.name();
+    if name != FIRST_VALUE && name != LAST_VALUE {
+        return None;
+    }
+    let AggregateFunctionParams {
+        args,
+        distinct,
+        filter,
+        order_by,
+        null_treatment,
+    } = params;
+
+    // DISTINCT / FILTER would break the shared scan, and IGNORE NULLS cannot 
be
+    // reproduced through a single struct (it would skip rows where the whole
+    // struct is null rather than where the individual value is null).
+    if *distinct
+        || filter.is_some()
+        || args.len() != 1
+        || order_by.is_empty()
+        || *null_treatment == Some(NullTreatment::IgnoreNulls)
+    {
+        return None;
+    }
+
+    Some(Coalesceable {
+        key: (name.to_string(), order_by.clone(), *null_treatment),
+        func: Arc::clone(func),
+        value: args[0].clone(),
+    })
+}
+
+impl OptimizerRule for CoalesceFirstLast {
+    fn name(&self) -> &str {
+        "coalesce_first_last"
+    }
+
+    fn apply_order(&self) -> Option<ApplyOrder> {
+        Some(ApplyOrder::BottomUp)
+    }
+
+    fn rewrite(
+        &self,
+        plan: LogicalPlan,
+        config: &dyn OptimizerConfig,
+    ) -> Result<Transformed<LogicalPlan>> {
+        if !config.options().optimizer.enable_coalesce_first_last {
+            return Ok(Transformed::no(plan));
+        }
+
+        let LogicalPlan::Aggregate(aggregate) = plan else {
+            return Ok(Transformed::no(plan));
+        };
+
+        // Grouping sets add an internal grouping-id column and distinct
+        // group-by semantics; this rule declines to coalesce them (consistent
+        // with the other cases it skips).
+        if matches!(aggregate.group_expr.as_slice(), [Expr::GroupingSet(_)]) {
+            return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate)));
+        }
+
+        let classified: Vec<Option<Coalesceable>> =
+            aggregate.aggr_expr.iter().map(classify).collect();
+
+        let mut buckets: IndexMap<BucketKey, Vec<usize>> = IndexMap::new();
+        for (i, c) in classified.iter().enumerate() {
+            if let Some(c) = c {
+                buckets.entry(c.key.clone()).or_default().push(i);
+            }
+        }
+        buckets.retain(|_, idxs| idxs.len() >= 2);
+        if buckets.is_empty() {
+            return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate)));
+        }

Review Comment:
   nit: you can probably make this a bit cleaner with a fold + filter + collect:
   ```
   let buckets: IndexMap<BucketKey, Vec<usize>> = 
classified.iter().enumerate().filter_map(|i, c| c.map(|c| (c.key.clone(), 
i))).fold(IndexMap::new(), |mut buckets, (key, i)| { 
buckets.entry(key).or_default().push(i); buckets }).into_iter().filter(filter 
out the len >= 2).collect();
   
   if buckets empty: return Transformed::no
   ```
   
   (the code above is just psuedocode and definitely won't compile lol but 
hopefully it's illustrative enough!)



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