zhuqi-lucas commented on code in PR #23682:
URL: https://github.com/apache/datafusion/pull/23682#discussion_r3694760978


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

Review Comment:
   Worth one more sentence here: with duplicate `ORDER BY` keys, the flag-on 
and flag-off plans may pick **different (equally valid) tied rows**. Each path 
breaks ties deterministically on its own (`FirstValueAccumulator::update_batch` 
keeps the incumbent on equal keys, `merge_batch` takes the first minimal 
state), but the two paths don't guarantee the *same* choice as each other — so 
someone diffing results with the flag toggled could see a difference on tied 
keys and file it as a bug. A doc note here preempts that report.



##########
datafusion/sqllogictest/test_files/coalesce_first_last.slt:
##########
@@ -0,0 +1,84 @@
+# 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.
+
+# Data with multiple groups, NULL value cells, and a unique ORDER BY key.
+statement ok
+CREATE TABLE t(p int, a int, b int, o int) AS VALUES

Review Comment:
   The unique-`o` data here deliberately avoids ties (👍), but that leaves the 
tie path in the struct-valued accumulator unexercised. You can test it 
deterministically by duplicating an *entire row* — same `ORDER BY` key **and** 
same values — so the assertion holds regardless of which tied row wins:
   
   ```sql
   CREATE TABLE ties(p int, a int, b int, o int) AS VALUES
   (1, 10, 100, 1), (1, 10, 100, 1), (1, 30, 300, 2);
   ```
   
   (`first_value(a)`/`first_value(b)` are then provably `10`/`100` under any 
tie resolution.)



##########
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),

Review Comment:
   `Some(RespectNulls)` and `None` are semantically identical (the planner 
emits `Some(RespectNulls)` for an explicit `RESPECT NULLS`, `None` otherwise), 
but they land in different buckets — so `first_value(a ORDER BY o)` and 
`first_value(b ORDER BY o RESPECT NULLS)` miss coalescing. Consider normalizing 
the key, e.g. `null_treatment.unwrap_or(NullTreatment::RespectNulls)` (with 
`BucketKey` becoming `(String, Vec<Sort>, NullTreatment)` and the destructuring 
below adjusted). The `IgnoreNulls` bail above already guarantees only 
respect-nulls members reach this point.



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