Skip to main content

common_function/aggrs/
aggr_wrapper.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Wrapper for making aggregate functions out of state/merge functions of original aggregate functions.
16//!
17//! i.e. for a aggregate function `foo`, we will have a state function `foo_state` and a merge function `foo_merge`.
18//!
19//! `foo_state`'s input args is the same as `foo`'s, and its output is a state object.
20//! Note that `foo_state` might have multiple output columns, so it's a struct array
21//! that each output column is a struct field.
22//! `foo_merge`'s input arg is the same as `foo_state`'s output, and its output is the same as `foo`'s input.
23//!
24
25use std::collections::HashSet;
26use std::hash::{Hash, Hasher};
27use std::sync::Arc;
28
29use arrow::array::{ArrayData, ArrayRef, BooleanArray, StructArray, make_array};
30use arrow_schema::{FieldRef, Fields};
31use common_telemetry::debug;
32use datafusion::functions_aggregate::all_default_aggregate_functions;
33use datafusion::functions_aggregate::count::Count;
34use datafusion::functions_aggregate::min_max::{Max, Min};
35use datafusion::optimizer::AnalyzerRule;
36use datafusion::optimizer::analyzer::type_coercion::TypeCoercion;
37use datafusion_common::{Column, ScalarValue};
38use datafusion_expr::expr::{AggregateFunction, AggregateFunctionParams};
39use datafusion_expr::function::StateFieldsArgs;
40use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
41use datafusion_expr::{
42    Accumulator, Aggregate, AggregateUDF, AggregateUDFImpl, EmitTo, Expr, ExprSchemable,
43    GroupsAccumulator, LogicalPlan, Signature,
44};
45use datafusion_physical_expr::aggregate::{AggregateFunctionExpr, LoweredAggregateBuilder};
46use datatypes::arrow::datatypes::{DataType, Field};
47
48use crate::aggrs::aggr_wrapper::fix_order::FixStateUdafOrderingAnalyzer;
49use crate::function_registry::{FUNCTION_REGISTRY, FunctionRegistry};
50
51pub mod fix_order;
52#[cfg(test)]
53mod tests;
54
55/// Checks the builtin COUNT identity, including inside its distributed state wrapper.
56pub fn is_builtin_count_or_state(function: &AggregateUDF) -> bool {
57    let inner = function.inner();
58    inner.is::<Count>()
59        || inner
60            .downcast_ref::<StateWrapper>()
61            .is_some_and(|state| state.inner().inner().is::<Count>())
62}
63
64/// Returns the name of the state function for the given aggregate function name.
65/// The state function is used to compute the state of the aggregate function.
66/// The state function's name is in the format `__<aggr_name>_state
67pub fn aggr_state_func_name(aggr_name: &str) -> String {
68    format!("__{}_state", aggr_name)
69}
70
71/// Returns the name of the merge function for the given aggregate function name.
72/// The merge function is used to merge the states of the state functions.
73/// The merge function's name is in the format `__<aggr_name>_merge
74pub fn aggr_merge_func_name(aggr_name: &str) -> String {
75    format!("__{}_merge", aggr_name)
76}
77
78/// Returns the globally registered name used to merge a delta state with a
79/// persisted state.
80pub fn aggr_delta_merge_func_name(state_aggregate_name: &str) -> String {
81    format!("__{}_delta_merge", state_aggregate_name)
82}
83
84/// Check if the given aggregate expression is steppable.
85/// As in if it can be split into multiple steps:
86/// i.e. on datanode first call `state(input)` then
87/// on frontend call `calc(merge(state))` to get the final result.
88pub fn is_all_aggr_exprs_steppable(aggr_exprs: &[Expr]) -> bool {
89    aggr_exprs.iter().all(|expr| {
90        if let Some(aggr_func) = get_aggr_func(expr) {
91            if aggr_func.params.distinct {
92                // Distinct aggregate functions are not steppable(yet).
93                // TODO(discord9): support distinct aggregate functions.
94                return false;
95            }
96
97            // DataFusion only sorts the input of an aggregate with a hard ordering requirement
98            // when the requirement is already satisfied or the aggregate has a reverse
99            // expression (apache/datafusion#25676). The state wrapper has none, so e.g.
100            // `nth_value(.. ORDER BY ..)` would read unsorted input on datanodes. Ordered-set
101            // aggregates like `approx_percentile_cont(..) WITHIN GROUP (ORDER BY ..)` are
102            // exempt: their ORDER BY names the value, and they don't need sorted input.
103            if !aggr_func.params.order_by.is_empty()
104                && aggr_func.func.order_sensitivity().hard_requires()
105                && !aggr_func.func.supports_within_group_clause()
106            {
107                return false;
108            }
109
110            // whether the corresponding state function exists in the registry
111            FUNCTION_REGISTRY.is_aggr_func_exist(&aggr_state_func_name(aggr_func.func.name()))
112        } else {
113            false
114        }
115    })
116}
117
118pub fn get_aggr_func(expr: &Expr) -> Option<&datafusion_expr::expr::AggregateFunction> {
119    let mut expr_ref = expr;
120    while let Expr::Alias(alias) = expr_ref {
121        expr_ref = &alias.expr;
122    }
123    if let Expr::AggregateFunction(aggr_func) = expr_ref {
124        Some(aggr_func)
125    } else {
126        None
127    }
128}
129
130/// A wrapper to make an aggregate function out of the state and merge functions of the original aggregate function.
131/// It contains the original aggregate function, the state functions, and the merge function.
132///
133/// Notice state functions may have multiple output columns, so it's return type is always a struct array, and the merge function is used to merge the states of the state functions.
134#[derive(Debug, Clone)]
135pub struct StateMergeHelper;
136
137/// A struct to hold the two aggregate plans, one for the state function(lower) and one for the merge function(upper).
138#[allow(unused)]
139#[derive(Debug, Clone)]
140pub struct StepAggrPlan {
141    /// Upper merge plan, which is the aggregate plan that merges the states of the state function.
142    pub upper_merge: LogicalPlan,
143    /// Lower state plan, which is the aggregate plan that computes the state of the aggregate function.
144    pub lower_state: LogicalPlan,
145}
146
147impl StateMergeHelper {
148    /// Register all the `state` function of supported aggregate functions.
149    /// Note that can't register `merge` function here, as it needs to be created from the original aggregate function with given input types.
150    pub fn register(registry: &FunctionRegistry) {
151        let all_default = all_default_aggregate_functions();
152        let greptime_custom_aggr_functions = registry.aggregate_functions();
153
154        // if our custom aggregate function have the same name as the default aggregate function, we will override it.
155        let supported = all_default
156            .into_iter()
157            .chain(greptime_custom_aggr_functions.into_iter().map(Arc::new))
158            .collect::<Vec<_>>();
159        debug!(
160            "Registering state functions for supported: {:?}",
161            supported.iter().map(|f| f.name()).collect::<Vec<_>>()
162        );
163
164        let state_func = supported.into_iter().filter_map(|f| {
165            StateWrapper::new((*f).clone())
166                .inspect_err(
167                    |e| common_telemetry::error!(e; "Failed to register state function for {:?}", f),
168                )
169                .ok()
170                .map(AggregateUDF::new_from_impl)
171        });
172
173        for func in state_func {
174            registry.register_aggr(func);
175        }
176    }
177
178    /// Split an aggregate plan into two aggregate plans, one for the state function and one for the merge function.
179    ///
180    pub fn split_aggr_node(aggr_plan: Aggregate) -> datafusion_common::Result<StepAggrPlan> {
181        let aggr = {
182            // certain aggr func need type coercion to work correctly, so we need to analyze the plan first.
183            let aggr_plan = TypeCoercion::new().analyze(
184                LogicalPlan::Aggregate(aggr_plan).clone(),
185                &Default::default(),
186            )?;
187            if let LogicalPlan::Aggregate(aggr) = aggr_plan {
188                aggr
189            } else {
190                return Err(datafusion_common::DataFusionError::Internal(format!(
191                    "Failed to coerce expressions in aggregate plan, expected Aggregate, got: {:?}",
192                    aggr_plan
193                )));
194            }
195        };
196        // (unaliased state expression, output column name)
197        let mut lower_states: Vec<(Expr, String)> = vec![];
198        let mut lower_output_names: HashSet<String> = aggr
199            .group_expr
200            .iter()
201            .map(|e| e.qualified_name().1)
202            .collect();
203        let mut upper_aggr_exprs = vec![];
204
205        // group exprs for upper plan should refer to the output group expr as column from lower plan
206        // to avoid re-compute group exprs again.
207        let upper_group_exprs = aggr
208            .group_expr
209            .iter()
210            .map(|c| c.qualified_name())
211            .map(|(r, c)| Expr::Column(Column::new(r, c)))
212            .collect();
213
214        for aggr_expr in aggr.aggr_expr.iter() {
215            let Some(aggr_func) = get_aggr_func(aggr_expr) else {
216                return Err(datafusion_common::DataFusionError::NotImplemented(format!(
217                    "Unsupported aggregate expression for step aggr optimize: {:?}",
218                    aggr_expr
219                )));
220            };
221
222            let original_input_fields = aggr_func
223                .params
224                .args
225                .iter()
226                .map(|e| e.to_field(&aggr.input.schema()).map(|(_, field)| field))
227                .collect::<Result<Vec<_>, _>>()?;
228
229            // first create the state function from the original aggregate function.
230            let state_func = StateWrapper::new((*aggr_func.func).clone())?;
231
232            let expr = AggregateFunction {
233                func: Arc::new(state_func.into()),
234                params: aggr_func.params.clone(),
235            };
236            let expr = Expr::AggregateFunction(expr);
237
238            // The state column is named after the unaliased state expression, which can
239            // repeat even though the original output names are unique: a name-preserving
240            // rewrite such as `count(*)` -> `count(ts) AS count(*)` can make two aggregates
241            // share one state expression, and schema names hide casts, so
242            // `count(CAST(ts AS Int64))` is named `count(t.ts)` too. Identical states are
243            // computed once; a different state with a taken name gets a numeric suffix.
244            let lower_state_output_col_name =
245                if let Some((_, name)) = lower_states.iter().find(|(e, _)| *e == expr) {
246                    name.clone()
247                } else {
248                    let base = expr.schema_name().to_string();
249                    let mut name = base.clone();
250                    let mut suffix = 0;
251                    while lower_output_names.contains(&name) {
252                        suffix += 1;
253                        name = format!("{base}_{suffix}");
254                    }
255                    lower_output_names.insert(name.clone());
256                    lower_states.push((expr, name.clone()));
257                    name
258                };
259
260            // then create the merge function using the physical expression of the original aggregate function
261            let (name, human_display) = match aggr_expr {
262                Expr::Alias(alias) => (alias.name.clone(), aggr_expr.human_display().to_string()),
263                Expr::AggregateFunction(_) => (
264                    aggr_expr.schema_name().to_string(),
265                    aggr_expr.human_display().to_string(),
266                ),
267                _ => unreachable!("aggregate expression was validated above"),
268            };
269            let original_phy_expr = LoweredAggregateBuilder::new(
270                aggr_expr,
271                aggr.input.schema(),
272                aggr.input.schema().as_arrow(),
273                &Default::default(),
274                &PhysicalPlanningContext::default(),
275            )
276            .with_name(name)
277            .with_human_display(human_display)
278            .build()?
279            .aggregate;
280
281            let merge_func = MergeWrapper::new(
282                (*aggr_func.func).clone(),
283                original_phy_expr,
284                original_input_fields,
285            )?;
286            let arg = Expr::Column(Column::new_unqualified(lower_state_output_col_name));
287            let expr = AggregateFunction {
288                func: Arc::new(merge_func.into()),
289                // notice filter/order_by is not supported in the merge function, as it's not meaningful to have them in the merge phase.
290                // do notice this order by is only removed in the outer logical plan, the physical plan still have order by and hence
291                // can create correct accumulator with order by.
292                params: AggregateFunctionParams {
293                    args: vec![arg],
294                    distinct: aggr_func.params.distinct,
295                    filter: None,
296                    order_by: vec![],
297                    null_treatment: aggr_func.params.null_treatment,
298                },
299            };
300
301            // alias to the original aggregate expr's schema name, so parent plan can refer to it
302            // correctly.
303            let expr = Expr::AggregateFunction(expr).alias(aggr_expr.schema_name().to_string());
304            upper_aggr_exprs.push(expr);
305        }
306
307        let mut lower = aggr.clone();
308        lower.aggr_expr = lower_states
309            .into_iter()
310            .map(|(expr, name)| {
311                if expr.schema_name().to_string() == name {
312                    expr
313                } else {
314                    expr.alias(name)
315                }
316            })
317            .collect();
318        let lower_plan = LogicalPlan::Aggregate(lower);
319
320        // update aggregate's output schema
321        let lower_plan = lower_plan.recompute_schema()?;
322
323        // should only affect two udaf `first_value/last_value`
324        // which only them have meaningful order by field
325        let fixed_lower_plan =
326            FixStateUdafOrderingAnalyzer.analyze(lower_plan, &Default::default())?;
327
328        let upper = Aggregate::try_new(
329            Arc::new(fixed_lower_plan.clone()),
330            upper_group_exprs,
331            upper_aggr_exprs.clone(),
332        )?;
333        let aggr_plan = LogicalPlan::Aggregate(aggr);
334
335        // upper schema's output schema should be the same as the original aggregate plan's output schema
336        let upper_check = upper;
337        let upper_plan = LogicalPlan::Aggregate(upper_check).recompute_schema()?;
338        if *upper_plan.schema() != *aggr_plan.schema() {
339            return Err(datafusion_common::DataFusionError::Internal(format!(
340                "Upper aggregate plan's schema is not the same as the original aggregate plan's schema: \n[transformed]:{}\n[original]:{}",
341                upper_plan.schema(),
342                aggr_plan.schema()
343            )));
344        }
345
346        Ok(StepAggrPlan {
347            lower_state: fixed_lower_plan,
348            upper_merge: upper_plan,
349        })
350    }
351}
352
353/// Wrapper to make an aggregate function out of a state function.
354#[derive(Debug, Clone, PartialEq, Eq, Hash)]
355pub struct StateWrapper {
356    inner: AggregateUDF,
357    name: String,
358    /// Default to empty, might get fixed by analyzer later
359    ordering: Vec<FieldRef>,
360    /// Default to false, might get fixed by analyzer later
361    distinct: bool,
362}
363
364impl StateWrapper {
365    /// `state_index`: The index of the state in the output of the state function.
366    pub fn new(inner: AggregateUDF) -> datafusion_common::Result<Self> {
367        let name = aggr_state_func_name(inner.name());
368        Ok(Self {
369            inner,
370            name,
371            ordering: vec![],
372            distinct: false,
373        })
374    }
375
376    pub fn inner(&self) -> &AggregateUDF {
377        &self.inner
378    }
379
380    /// Deduce the return type of the original aggregate function
381    /// based on the accumulator arguments.
382    ///
383    pub fn deduce_aggr_return_type(
384        &self,
385        acc_args: &datafusion_expr::function::AccumulatorArgs,
386    ) -> datafusion_common::Result<FieldRef> {
387        let input_fields = acc_args
388            .exprs
389            .iter()
390            .map(|e| e.return_field(acc_args.schema))
391            .collect::<Result<Vec<_>, _>>()?;
392        self.inner.return_field(&input_fields).inspect_err(|e| {
393            common_telemetry::error!(
394                "StateWrapper: {:#?}\nacc_args:{:?}\nerror:{:?}",
395                &self,
396                &acc_args,
397                e
398            );
399        })
400    }
401
402    fn fix_inner_acc_args<'b>(
403        &self,
404        mut acc_args: datafusion_expr::function::AccumulatorArgs<'b>,
405    ) -> datafusion_common::Result<datafusion_expr::function::AccumulatorArgs<'b>> {
406        acc_args.return_field = self.deduce_aggr_return_type(&acc_args)?;
407        Ok(acc_args)
408    }
409}
410
411impl AggregateUDFImpl for StateWrapper {
412    fn accumulator<'a, 'b>(
413        &'a self,
414        acc_args: datafusion_expr::function::AccumulatorArgs<'b>,
415    ) -> datafusion_common::Result<Box<dyn Accumulator>> {
416        // fix and recover proper acc args for the original aggregate function.
417        let state_type = acc_args.return_type().clone();
418        let inner = self.inner.accumulator(self.fix_inner_acc_args(acc_args)?)?;
419
420        Ok(Box::new(StateAccum::new(inner, state_type)?))
421    }
422
423    fn groups_accumulator_supported(
424        &self,
425        acc_args: datafusion_expr::function::AccumulatorArgs,
426    ) -> bool {
427        self.fix_inner_acc_args(acc_args)
428            .map(|args| self.inner.inner().groups_accumulator_supported(args))
429            .unwrap_or(false)
430    }
431
432    fn create_groups_accumulator(
433        &self,
434        acc_args: datafusion_expr::function::AccumulatorArgs,
435    ) -> datafusion_common::Result<Box<dyn GroupsAccumulator>> {
436        let state_type = acc_args.return_type().clone();
437        let inner = self
438            .inner
439            .inner()
440            .create_groups_accumulator(self.fix_inner_acc_args(acc_args)?)?;
441        Ok(Box::new(StateGroupsAccum::new(inner, state_type)?))
442    }
443
444    fn name(&self) -> &str {
445        self.name.as_str()
446    }
447
448    fn is_nullable(&self) -> bool {
449        self.inner.is_nullable()
450    }
451
452    /// Return state_fields as the output struct type.
453    ///
454    fn return_type(&self, arg_types: &[DataType]) -> datafusion_common::Result<DataType> {
455        let input_fields = &arg_types
456            .iter()
457            .map(|x| Arc::new(Field::new("x", x.clone(), false)))
458            .collect::<Vec<_>>();
459
460        let state_fields_args = StateFieldsArgs {
461            name: self.inner().name(),
462            input_fields,
463            return_field: self.inner.return_field(input_fields)?,
464            // those args are also needed as they are vital to construct the state fields correctly.
465            ordering_fields: &self.ordering,
466            is_distinct: self.distinct,
467        };
468        let state_fields = self.inner.state_fields(state_fields_args)?;
469
470        let state_fields = state_fields
471            .into_iter()
472            .map(|f| {
473                let mut f = f.as_ref().clone();
474                // since state can be null when no input rows, so make all fields nullable
475                f.set_nullable(true);
476                Arc::new(f)
477            })
478            .collect::<Vec<_>>();
479
480        let struct_field = DataType::Struct(state_fields.into());
481        Ok(struct_field)
482    }
483
484    /// The state function's output fields are the same as the original aggregate function's state fields.
485    fn state_fields(
486        &self,
487        args: datafusion_expr::function::StateFieldsArgs,
488    ) -> datafusion_common::Result<Vec<FieldRef>> {
489        let state_fields_args = StateFieldsArgs {
490            name: args.name,
491            input_fields: args.input_fields,
492            return_field: self.inner.return_field(args.input_fields)?,
493            ordering_fields: args.ordering_fields,
494            is_distinct: args.is_distinct,
495        };
496        self.inner.state_fields(state_fields_args)
497    }
498
499    /// The state function's signature is the same as the original aggregate function's signature,
500    fn signature(&self) -> &Signature {
501        self.inner.signature()
502    }
503
504    /// Coerce types also do nothing, as optimizer should be able to already make struct types
505    fn coerce_types(&self, arg_types: &[DataType]) -> datafusion_common::Result<Vec<DataType>> {
506        self.inner.coerce_types(arg_types)
507    }
508
509    fn value_from_stats(
510        &self,
511        statistics_args: &datafusion_expr::StatisticsArgs,
512    ) -> Option<ScalarValue> {
513        let inner = self.inner().inner();
514        // only count/min/max need special handling here, for getting result from statistics
515        // the result of count/min/max is also the result of count_state so can return directly
516        let can_use_stat = inner.is::<Count>() || inner.is::<Max>() || inner.is::<Min>();
517        if !can_use_stat {
518            return None;
519        }
520
521        // fix return type by extract the first field's data type from the struct type
522        let state_type = if let DataType::Struct(fields) = &statistics_args.return_type {
523            if fields.is_empty() {
524                return None;
525            }
526            fields[0].data_type().clone()
527        } else {
528            return None;
529        };
530
531        let fixed_args = datafusion_expr::StatisticsArgs {
532            statistics: statistics_args.statistics,
533            return_type: &state_type,
534            is_distinct: statistics_args.is_distinct,
535            exprs: statistics_args.exprs,
536        };
537
538        let ret = self.inner().value_from_stats(&fixed_args)?;
539
540        // wrap the result into struct scalar value
541        let fields = if let DataType::Struct(fields) = &statistics_args.return_type {
542            fields
543        } else {
544            return None;
545        };
546
547        let array = ret.to_array().ok()?;
548
549        let struct_array = StructArray::new(fields.clone(), vec![array], None);
550        let ret = ScalarValue::Struct(Arc::new(struct_array));
551        Some(ret)
552    }
553}
554
555/// The wrapper's input is the same as the original aggregate function's input,
556/// and the output is the state function's output.
557#[derive(Debug)]
558pub struct StateAccum {
559    inner: Box<dyn Accumulator>,
560    state_fields: Fields,
561}
562
563pub struct StateGroupsAccum {
564    inner: Box<dyn GroupsAccumulator>,
565    state_fields: Fields,
566}
567
568impl StateGroupsAccum {
569    fn new(
570        inner: Box<dyn GroupsAccumulator>,
571        state_type: DataType,
572    ) -> datafusion_common::Result<Self> {
573        let DataType::Struct(fields) = state_type else {
574            return Err(datafusion_common::DataFusionError::Internal(format!(
575                "Expected a struct type for state, got: {:?}",
576                state_type
577            )));
578        };
579        Ok(Self {
580            inner,
581            state_fields: fields,
582        })
583    }
584
585    fn wrap_state_arrays(&self, arrays: Vec<ArrayRef>) -> datafusion_common::Result<ArrayRef> {
586        Ok(Arc::new(state_struct_array(&self.state_fields, arrays)?))
587    }
588}
589
590impl GroupsAccumulator for StateGroupsAccum {
591    fn update_batch(
592        &mut self,
593        values: &[ArrayRef],
594        group_indices: &[usize],
595        opt_filter: Option<&BooleanArray>,
596        total_num_groups: usize,
597    ) -> datafusion_common::Result<()> {
598        self.inner
599            .update_batch(values, group_indices, opt_filter, total_num_groups)
600    }
601
602    fn merge_batch(
603        &mut self,
604        values: &[ArrayRef],
605        group_indices: &[usize],
606        total_num_groups: usize,
607    ) -> datafusion_common::Result<()> {
608        self.inner
609            .merge_batch(values, group_indices, total_num_groups)
610    }
611
612    fn evaluate(&mut self, emit_to: EmitTo) -> datafusion_common::Result<ArrayRef> {
613        let state = self.inner.state(emit_to)?;
614        self.wrap_state_arrays(state)
615    }
616
617    fn state(&mut self, emit_to: EmitTo) -> datafusion_common::Result<Vec<ArrayRef>> {
618        self.inner.state(emit_to)
619    }
620
621    fn convert_to_state(
622        &self,
623        values: &[ArrayRef],
624        opt_filter: Option<&BooleanArray>,
625    ) -> datafusion_common::Result<Vec<ArrayRef>> {
626        self.inner.convert_to_state(values, opt_filter)
627    }
628
629    fn size(&self) -> usize {
630        self.inner.size()
631    }
632}
633
634/// Wraps the state arrays of an accumulator into a struct of the declared state fields.
635///
636/// The declared state type is derived from logical expressions, while the accumulator names
637/// nested fields after physical expressions. For example, `array_agg(v ORDER BY ts)` declares
638/// its orderings as `List(Struct("ts": ..))` but produces `List(Struct("ts@0": ..))`. Arrays that
639/// differ only in nested field names are cast to the declared type; any other difference is an
640/// error.
641fn state_struct_array(
642    state_fields: &Fields,
643    arrays: Vec<ArrayRef>,
644) -> datafusion_common::Result<StructArray> {
645    if arrays.len() != state_fields.len() {
646        return Err(datafusion_common::DataFusionError::Internal(format!(
647            "Expected {} state arrays for fields {:?}, got {}",
648            state_fields.len(),
649            state_fields,
650            arrays.len()
651        )));
652    }
653    let arrays = arrays
654        .into_iter()
655        .zip(state_fields.iter())
656        .map(|(array, field)| {
657            let expected = field.data_type();
658            if array.data_type() == expected {
659                Ok(array)
660            } else if array.data_type().equals_datatype(expected) {
661                Ok(make_array(relabel_nested_fields(
662                    array.to_data(),
663                    expected,
664                )?))
665            } else {
666                Err(datafusion_common::DataFusionError::Internal(format!(
667                    "State field `{}` expects type {expected}, but the accumulator produced {}",
668                    field.name(),
669                    array.data_type()
670                )))
671            }
672        })
673        .collect::<datafusion_common::Result<Vec<_>>>()?;
674    Ok(StructArray::try_new(state_fields.clone(), arrays, None)?)
675}
676
677/// Rebuilds `data` with the type `target`, which must match it position by position apart
678/// from nested field names and metadata. Unlike a cast, children are never matched by name.
679fn relabel_nested_fields(
680    data: ArrayData,
681    target: &DataType,
682) -> datafusion_common::Result<ArrayData> {
683    let child_types = match target {
684        DataType::List(field)
685        | DataType::LargeList(field)
686        | DataType::FixedSizeList(field, _)
687        | DataType::Map(field, _) => vec![field.data_type()],
688        DataType::Struct(fields) => fields.iter().map(|f| f.data_type()).collect(),
689        _ if data.child_data().is_empty() => vec![],
690        _ => {
691            return Err(datafusion_common::DataFusionError::NotImplemented(format!(
692                "Relabeling nested fields of {target}"
693            )));
694        }
695    };
696    let children = data
697        .child_data()
698        .iter()
699        .zip(child_types)
700        .map(|(child, child_type)| relabel_nested_fields(child.clone(), child_type))
701        .collect::<datafusion_common::Result<Vec<_>>>()?;
702    Ok(data
703        .into_builder()
704        .data_type(target.clone())
705        .child_data(children)
706        .build()?)
707}
708
709impl StateAccum {
710    pub fn new(
711        inner: Box<dyn Accumulator>,
712        state_type: DataType,
713    ) -> datafusion_common::Result<Self> {
714        let DataType::Struct(fields) = state_type else {
715            return Err(datafusion_common::DataFusionError::Internal(format!(
716                "Expected a struct type for state, got: {:?}",
717                state_type
718            )));
719        };
720        Ok(Self {
721            inner,
722            state_fields: fields,
723        })
724    }
725}
726
727impl Accumulator for StateAccum {
728    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
729        let state = self.inner.state()?;
730
731        let array = state
732            .iter()
733            .map(|s| s.to_array())
734            .collect::<Result<Vec<_>, _>>()?;
735        let struct_array = state_struct_array(&self.state_fields, array)?;
736        Ok(ScalarValue::Struct(Arc::new(struct_array)))
737    }
738
739    fn merge_batch(
740        &mut self,
741        states: &[datatypes::arrow::array::ArrayRef],
742    ) -> datafusion_common::Result<()> {
743        self.inner.merge_batch(states)
744    }
745
746    fn update_batch(
747        &mut self,
748        values: &[datatypes::arrow::array::ArrayRef],
749    ) -> datafusion_common::Result<()> {
750        self.inner.update_batch(values)
751    }
752
753    fn size(&self) -> usize {
754        self.inner.size()
755    }
756
757    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
758        self.inner.state()
759    }
760}
761
762/// A globally registerable wrapper for a state-family merge UDAF.
763///
764/// The wrapped merge function has the family contract `P..., State`. This
765/// wrapper exposes `P..., delta_state, persisted_state` and forwards the two
766/// state columns to the existing accumulator in that order. State values are
767/// opaque to this adapter; null is the inner merge family's identity value.
768#[derive(Debug, Clone)]
769pub(crate) struct DeltaMergeWrapper {
770    inner: AggregateUDF,
771    name: String,
772    signature: Signature,
773    inner_types: Vec<DataType>,
774    state_type: DataType,
775}
776
777impl DeltaMergeWrapper {
778    /// Build the wrapper for one of the explicitly supported exact merge UDAFs.
779    ///
780    /// The caller supplies the known merge signature, so construction cannot
781    /// fail while inspecting an arbitrary UDAF signature.
782    pub(crate) fn new(
783        inner: AggregateUDF,
784        state_name: &str,
785        inner_types: Vec<DataType>,
786        state_type: DataType,
787    ) -> Self {
788        let mut wrapper_types = inner_types.clone();
789        wrapper_types.push(state_type.clone());
790        Self {
791            name: aggr_delta_merge_func_name(state_name),
792            signature: Signature::exact(wrapper_types, inner.signature().volatility),
793            inner,
794            inner_types,
795            state_type,
796        }
797    }
798
799    fn resolve_inner_args(
800        &self,
801        input_fields: &[FieldRef],
802    ) -> datafusion_common::Result<Vec<FieldRef>> {
803        if input_fields.len() != self.inner_types.len() + 1 {
804            return Err(datafusion_common::DataFusionError::Plan(
805                "delta merge requires parameters, delta state, and persisted state".to_string(),
806            ));
807        }
808        for (field, expected_type) in input_fields[..self.inner_types.len()]
809            .iter()
810            .zip(&self.inner_types)
811        {
812            if field.data_type() != expected_type {
813                return Err(datafusion_common::DataFusionError::Plan(format!(
814                    "delta merge argument type does not match its exact signature: {:?} != {expected_type:?}",
815                    field.data_type()
816                )));
817            }
818        }
819        let persisted = &input_fields[self.inner_types.len()];
820        if persisted.data_type() != &self.state_type && persisted.data_type() != &DataType::Null {
821            return Err(datafusion_common::DataFusionError::Plan(format!(
822                "persisted state type does not match the exact state type: {:?} != {:?}",
823                persisted.data_type(),
824                self.state_type
825            )));
826        }
827        Ok(input_fields[..self.inner_types.len()].to_vec())
828    }
829}
830
831impl AggregateUDFImpl for DeltaMergeWrapper {
832    fn accumulator<'a, 'b>(
833        &'a self,
834        acc_args: datafusion_expr::function::AccumulatorArgs<'b>,
835    ) -> datafusion_common::Result<Box<dyn Accumulator>> {
836        if acc_args.exprs.len() != acc_args.expr_fields.len() {
837            return Err(datafusion_common::DataFusionError::Plan(
838                "delta merge expression and field arities differ".to_string(),
839            ));
840        }
841        let inner_fields = self.resolve_inner_args(acc_args.expr_fields)?;
842        for (expr, expected_type) in acc_args.exprs.iter().zip(
843            self.inner_types
844                .iter()
845                .chain(std::iter::once(&self.state_type)),
846        ) {
847            if expr.data_type(acc_args.schema)? != *expected_type {
848                return Err(datafusion_common::DataFusionError::Internal(
849                    "delta merge physical expression type is not resolved".to_string(),
850                ));
851            }
852        }
853        let state_index = self.inner_types.len() - 1;
854        let inner_args = datafusion_expr::function::AccumulatorArgs {
855            return_field: acc_args.return_field,
856            schema: acc_args.schema,
857            ignore_nulls: acc_args.ignore_nulls,
858            order_bys: acc_args.order_bys,
859            is_reversed: acc_args.is_reversed,
860            name: self.inner.name(),
861            is_distinct: acc_args.is_distinct,
862            exprs: &acc_args.exprs[..=state_index],
863            expr_fields: &inner_fields,
864        };
865        Ok(Box::new(DeltaMergeAccum {
866            inner: self.inner.accumulator(inner_args)?,
867            params: state_index,
868        }))
869    }
870
871    fn name(&self) -> &str {
872        &self.name
873    }
874
875    fn is_nullable(&self) -> bool {
876        self.inner.is_nullable()
877    }
878
879    fn return_type(&self, arg_types: &[DataType]) -> datafusion_common::Result<DataType> {
880        let fields = arg_types
881            .iter()
882            .enumerate()
883            .map(|(index, data_type)| {
884                Arc::new(Field::new(index.to_string(), data_type.clone(), true))
885            })
886            .collect::<Vec<_>>();
887        let inner_fields = self.resolve_inner_args(&fields)?;
888        self.inner.return_type(
889            &inner_fields
890                .iter()
891                .map(|field| field.data_type().clone())
892                .collect::<Vec<_>>(),
893        )
894    }
895
896    fn return_field(&self, arg_fields: &[FieldRef]) -> datafusion_common::Result<FieldRef> {
897        let inner_fields = self.resolve_inner_args(arg_fields)?;
898        self.inner.return_field(&inner_fields)
899    }
900
901    fn signature(&self) -> &Signature {
902        &self.signature
903    }
904
905    fn state_fields(
906        &self,
907        args: datafusion_expr::function::StateFieldsArgs,
908    ) -> datafusion_common::Result<Vec<FieldRef>> {
909        let inner_fields = self.resolve_inner_args(args.input_fields)?;
910        self.inner
911            .state_fields(datafusion_expr::function::StateFieldsArgs {
912                name: args.name,
913                input_fields: &inner_fields,
914                return_field: args.return_field,
915                ordering_fields: args.ordering_fields,
916                is_distinct: args.is_distinct,
917            })
918    }
919}
920
921impl PartialEq for DeltaMergeWrapper {
922    fn eq(&self, other: &Self) -> bool {
923        self.name == other.name && self.inner == other.inner
924    }
925}
926impl Eq for DeltaMergeWrapper {}
927impl Hash for DeltaMergeWrapper {
928    fn hash<H: Hasher>(&self, state: &mut H) {
929        self.name.hash(state);
930        self.inner.hash(state);
931    }
932}
933
934#[derive(Debug)]
935struct DeltaMergeAccum {
936    inner: Box<dyn Accumulator>,
937    params: usize,
938}
939
940impl Accumulator for DeltaMergeAccum {
941    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
942        self.inner.evaluate()
943    }
944
945    fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
946        if values.len() != self.params + 2 {
947            return Err(datafusion_common::DataFusionError::Plan(format!(
948                "delta merge expected {} arguments, got {}",
949                self.params + 2,
950                values.len()
951            )));
952        }
953        // Null-state identity is an inner family precondition. The wrapper
954        // forwards opaque states and never decodes or filters them.
955        let mut inner_values = values[..self.params + 1].to_vec();
956        self.inner.update_batch(&inner_values)?;
957        inner_values[self.params] = values[self.params + 1].clone();
958        self.inner.update_batch(&inner_values)
959    }
960
961    fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
962        self.inner.merge_batch(states)
963    }
964
965    fn size(&self) -> usize {
966        self.inner.size()
967    }
968
969    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
970        self.inner.state()
971    }
972}
973
974/// TODO(discord9): mark this function as non-ser/de able
975///
976/// This wrapper shouldn't be register as a udaf, as it contain extra data that is not serializable.
977/// and changes for different logical plans.
978#[derive(Debug, Clone)]
979pub struct MergeWrapper {
980    inner: AggregateUDF,
981    name: String,
982    merge_signature: Signature,
983    /// The original physical expression of the aggregate function, can't store the original aggregate function directly, as PhysicalExpr didn't implement Any
984    original_phy_expr: Arc<AggregateFunctionExpr>,
985    return_field: FieldRef,
986}
987impl MergeWrapper {
988    pub fn new(
989        inner: AggregateUDF,
990        original_phy_expr: Arc<AggregateFunctionExpr>,
991        original_input_fields: Vec<FieldRef>,
992    ) -> datafusion_common::Result<Self> {
993        let name = aggr_merge_func_name(inner.name());
994        // the input type is actually struct type, which is the state fields of the original aggregate function.
995        let merge_signature = Signature::user_defined(datafusion_expr::Volatility::Immutable);
996        let return_field = inner.return_field(&original_input_fields)?.clone();
997
998        Ok(Self {
999            inner,
1000            name,
1001            merge_signature,
1002            original_phy_expr,
1003            return_field,
1004        })
1005    }
1006
1007    pub fn inner(&self) -> &AggregateUDF {
1008        &self.inner
1009    }
1010}
1011
1012impl AggregateUDFImpl for MergeWrapper {
1013    fn accumulator<'a, 'b>(
1014        &'a self,
1015        acc_args: datafusion_expr::function::AccumulatorArgs<'b>,
1016    ) -> datafusion_common::Result<Box<dyn Accumulator>> {
1017        if acc_args.exprs.len() != 1
1018            || !matches!(
1019                acc_args.exprs[0].data_type(acc_args.schema)?,
1020                DataType::Struct(_)
1021            )
1022        {
1023            return Err(datafusion_common::DataFusionError::Internal(format!(
1024                "Expected one struct type as input, got: {:?}",
1025                acc_args.schema
1026            )));
1027        }
1028        let input_type = acc_args.exprs[0].data_type(acc_args.schema)?;
1029        let DataType::Struct(fields) = input_type else {
1030            return Err(datafusion_common::DataFusionError::Internal(format!(
1031                "Expected a struct type for input, got: {:?}",
1032                input_type
1033            )));
1034        };
1035
1036        let inner_accum = self.original_phy_expr.create_accumulator()?;
1037        Ok(Box::new(MergeAccum::new(inner_accum, &fields)))
1038    }
1039
1040    fn name(&self) -> &str {
1041        self.name.as_str()
1042    }
1043
1044    fn is_nullable(&self) -> bool {
1045        self.inner.is_nullable()
1046    }
1047
1048    /// Notice here the `arg_types` is actually the `state_fields`'s data types,
1049    /// so return fixed return type instead of using `arg_types` to determine the return type.
1050    fn return_type(&self, _arg_types: &[DataType]) -> datafusion_common::Result<DataType> {
1051        // The return type is the same as the original aggregate function's return type.
1052        Ok(self.return_field.data_type().clone())
1053    }
1054
1055    /// Similar to return_type, we just return the fixed return field.
1056    fn return_field(&self, _arg_fields: &[FieldRef]) -> datafusion_common::Result<FieldRef> {
1057        Ok(self.return_field.clone())
1058    }
1059
1060    fn signature(&self) -> &Signature {
1061        &self.merge_signature
1062    }
1063
1064    /// Coerce types also do nothing, as optimizer should be able to already make struct types
1065    fn coerce_types(&self, arg_types: &[DataType]) -> datafusion_common::Result<Vec<DataType>> {
1066        // just check if the arg_types are only one and is struct array
1067        if arg_types.len() != 1 || !matches!(arg_types.first(), Some(DataType::Struct(_))) {
1068            return Err(datafusion_common::DataFusionError::Internal(format!(
1069                "Expected one struct type as input, got: {:?}",
1070                arg_types
1071            )));
1072        }
1073        Ok(arg_types.to_vec())
1074    }
1075
1076    /// Just return the original aggregate function's state fields.
1077    fn state_fields(
1078        &self,
1079        _args: datafusion_expr::function::StateFieldsArgs,
1080    ) -> datafusion_common::Result<Vec<FieldRef>> {
1081        self.original_phy_expr.state_fields()
1082    }
1083}
1084
1085impl PartialEq for MergeWrapper {
1086    fn eq(&self, other: &Self) -> bool {
1087        self.inner == other.inner
1088    }
1089}
1090
1091impl Eq for MergeWrapper {}
1092
1093impl Hash for MergeWrapper {
1094    fn hash<H: Hasher>(&self, state: &mut H) {
1095        self.inner.hash(state);
1096    }
1097}
1098
1099/// The merge accumulator, which modify `update_batch`'s behavior to accept one struct array which
1100/// include the state fields of original aggregate function, and merge said states into original accumulator
1101/// the output is the same as original aggregate function
1102#[derive(Debug)]
1103pub struct MergeAccum {
1104    inner: Box<dyn Accumulator>,
1105    state_fields: Fields,
1106}
1107
1108impl MergeAccum {
1109    pub fn new(inner: Box<dyn Accumulator>, state_fields: &Fields) -> Self {
1110        Self {
1111            inner,
1112            state_fields: state_fields.clone(),
1113        }
1114    }
1115}
1116
1117impl Accumulator for MergeAccum {
1118    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
1119        self.inner.evaluate()
1120    }
1121
1122    fn merge_batch(&mut self, states: &[arrow::array::ArrayRef]) -> datafusion_common::Result<()> {
1123        self.inner.merge_batch(states)
1124    }
1125
1126    fn update_batch(&mut self, values: &[arrow::array::ArrayRef]) -> datafusion_common::Result<()> {
1127        let value = values.first().ok_or_else(|| {
1128            datafusion_common::DataFusionError::Internal("No values provided for merge".to_string())
1129        })?;
1130        // The input values are states from other accumulators, so we merge them.
1131        let struct_arr = value
1132            .as_any()
1133            .downcast_ref::<StructArray>()
1134            .ok_or_else(|| {
1135                datafusion_common::DataFusionError::Internal(format!(
1136                    "Expected StructArray, got: {:?}",
1137                    value.data_type()
1138                ))
1139            })?;
1140        let fields = struct_arr.fields();
1141        if fields != &self.state_fields {
1142            debug!(
1143                "State fields mismatch, expected: {:?}, got: {:?}",
1144                self.state_fields, fields
1145            );
1146            // state fields mismatch might be acceptable by datafusion, continue
1147        }
1148
1149        // now fields should be the same, so we can merge the batch
1150        // by pass the columns as order should be the same
1151        let state_columns = struct_arr.columns();
1152        self.inner.merge_batch(state_columns)
1153    }
1154
1155    fn size(&self) -> usize {
1156        self.inner.size()
1157    }
1158
1159    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
1160        self.inner.state()
1161    }
1162}