zhuqi-lucas commented on code in PR #23682: URL: https://github.com/apache/datafusion/pull/23682#discussion_r3742917702
########## datafusion/optimizer/src/coalesce_first_last.rs: ########## @@ -0,0 +1,767 @@ +// 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. +/// +/// Ties are not guaranteed to break the same way with the rule on and off. Each +/// plan resolves them deterministically on its own, but the two do not guarantee +/// the same choice as each other, so duplicate `ORDER BY` keys can yield +/// different (equally valid) winners depending on the flag. +/// +/// 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. +// 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>, NullTreatment); + +struct Coalesceable { + key: BucketKey, + func: Arc<AggregateUDF>, + value: Expr, +} + +fn classify(expr: &Expr) -> Option<Coalesceable> { + // `aggr_expr` entries are an `AggregateFunction` or an `Alias` wrapping one + // (e.g. built via the DataFrame API), so unwrap to catch aliased peers. + 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 break the shared scan, and IGNORE NULLS can't go through + // one struct (it would skip whole-struct nulls, not per-value nulls). + if *distinct + || filter.is_some() + || args.len() != 1 + || order_by.is_empty() + || *null_treatment == Some(NullTreatment::IgnoreNulls) Review Comment: This `IGNORE NULLS` bail is exactly right — a single struct can only skip whole-struct nulls, not per-value nulls, so coalescing peers under `IGNORE NULLS` could change results. The concern is that nothing pins it: `grep -iE 'ignore nulls|distinct|filter' coalesce_first_last.slt` returns zero hits, so the whole `classify()` gate (this line, plus DISTINCT / FILTER / multi-arg / no-ORDER-BY) is currently untested — the positive cases all exercise the *coalesced* path, none assert the *declined* path. Could you add a negative case, most importantly for `IGNORE NULLS`? Something like two peers ```sql first_value(a ORDER BY o) IGNORE NULLS, first_value(b ORDER BY o) IGNORE NULLS ``` where `a` and `b` have their NULLs in different rows, with (1) an `EXPLAIN` showing they stay as two separate `first_value`s rather than one struct-valued aggregate, and (2) a result check that each column returns its own first *non-null* value. That locks the exact semantics this bail protects — a future refactor that accidentally merged them would then fail loudly instead of silently returning wrong data. A one-liner each for DISTINCT / FILTER staying uncoalesced would round it out. -- 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]
