Skip to main content

datafusion_physical_expr/
aggregate.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5pub(crate) mod groups_accumulator {
6    #[expect(unused_imports)]
7    pub(crate) mod accumulate {
8        pub use datafusion_functions_aggregate_common::aggregate::groups_accumulator::accumulate::NullState;
9    }
10    pub use datafusion_functions_aggregate_common::aggregate::groups_accumulator::{
11        GroupsAccumulatorAdapter, accumulate::NullState,
12    };
13}
14pub(crate) mod stats {
15    pub use datafusion_functions_aggregate_common::stats::StatsType;
16}
17pub mod utils {
18    pub use datafusion_functions_aggregate_common::utils::{
19        DecimalAverager, Hashable, get_accum_scalar_values_as_arrays, get_sort_options,
20        ordering_fields,
21    };
22}
23
24use std::fmt::Debug;
25use std::sync::Arc;
26
27use crate::expressions::Column;
28use crate::physical_expr::create_physical_sort_exprs;
29use crate::planner::{create_physical_expr, create_physical_exprs};
30
31use arrow::compute::SortOptions;
32use arrow::datatypes::{DataType, FieldRef, Schema, SchemaRef};
33use datafusion_common::metadata::FieldMetadata;
34use datafusion_common::{
35    DFSchema, Result, ScalarValue, assert_or_internal_err, internal_err, not_impl_err,
36};
37use datafusion_expr::execution_props::ExecutionProps;
38use datafusion_expr::expr::{
39    AggregateFunction, AggregateFunctionParams, NullTreatment, physical_name,
40};
41use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
42use datafusion_expr::{AggregateUDF, Expr, ReversedUDAF, SetMonotonicity};
43use datafusion_expr_common::accumulator::{Accumulator, AggregateMetrics};
44use datafusion_expr_common::groups_accumulator::GroupsAccumulator;
45use datafusion_expr_common::type_coercion::aggregates::check_arg_count;
46use datafusion_functions_aggregate_common::accumulator::{
47    AccumulatorArgs, StateFieldsArgs,
48};
49use datafusion_functions_aggregate_common::order::AggregateOrderSensitivity;
50use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
51use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
52
53#[derive(Debug, Clone)]
54struct AggregateHumanDisplay {
55    expression: String,
56    alias: Option<String>,
57}
58
59impl AggregateHumanDisplay {
60    fn try_new(
61        expression: Option<String>,
62        alias: Option<String>,
63        name: &str,
64    ) -> Result<Option<Self>> {
65        let alias = alias.filter(|alias| !alias.is_empty());
66        let Some(expression) = expression else {
67            if alias.is_some() {
68                return internal_err!(
69                    "AggregateExprBuilder::human_display must be provided when human_display_alias is set"
70                );
71            }
72            return Ok(None);
73        };
74
75        if expression.is_empty() {
76            if alias.is_some() {
77                return internal_err!(
78                    "AggregateExprBuilder::human_display must be non-empty when human_display_alias is set"
79                );
80            }
81            return Ok(None);
82        }
83
84        if let Some(alias) = alias.as_deref()
85            && alias != name
86        {
87            return internal_err!(
88                "aggregate human_display_alias must match aggregate name `{name}`: {alias}"
89            );
90        }
91
92        Ok(Some(Self { expression, alias }))
93    }
94
95    fn expression(&self) -> &str {
96        &self.expression
97    }
98
99    fn alias(&self) -> Option<&str> {
100        self.alias.as_deref()
101    }
102}
103
104/// Builder for physical [`AggregateFunctionExpr`]
105///
106/// `AggregateFunctionExpr` contains the information necessary to call
107/// an aggregate expression.
108#[derive(Debug, Clone)]
109pub struct AggregateExprBuilder {
110    fun: Arc<AggregateUDF>,
111    /// Physical expressions of the aggregate function
112    args: Vec<Arc<dyn PhysicalExpr>>,
113    alias: Option<String>,
114    output_metadata: Option<FieldMetadata>,
115    /// A human readable name
116    human_display: Option<String>,
117    /// Optional visible output alias for `human_display`.
118    human_display_alias: Option<String>,
119    /// Arrow Schema for the aggregate function
120    schema: SchemaRef,
121    /// The physical order by expressions
122    order_bys: Vec<PhysicalSortExpr>,
123    /// Whether to ignore null values
124    ignore_nulls: bool,
125    /// Whether is distinct aggregate function
126    is_distinct: bool,
127    /// Whether the expression is reversed
128    is_reversed: bool,
129}
130
131impl AggregateExprBuilder {
132    pub fn new(fun: Arc<AggregateUDF>, args: Vec<Arc<dyn PhysicalExpr>>) -> Self {
133        Self {
134            fun,
135            args,
136            alias: None,
137            output_metadata: None,
138            human_display: None,
139            human_display_alias: None,
140            schema: Arc::new(Schema::empty()),
141            order_bys: vec![],
142            ignore_nulls: false,
143            is_distinct: false,
144            is_reversed: false,
145        }
146    }
147
148    /// Constructs an `AggregateFunctionExpr` from the builder
149    ///
150    /// Note that an [`Self::alias`] must be provided before calling this method.
151    ///
152    /// # Example: Create an [`AggregateUDF`]
153    ///
154    /// In the following example, [`AggregateFunctionExpr`] will be built using [`AggregateExprBuilder`]
155    /// which provides a build function. Full example could be accessed from the source file.
156    ///
157    /// ```
158    /// # use std::any::Any;
159    /// # use std::sync::Arc;
160    /// # use arrow::datatypes::{DataType, FieldRef};
161    /// # use datafusion_common::{Result, ScalarValue};
162    /// # use datafusion_expr::{col, ColumnarValue, Documentation, Signature, Volatility, Expr};
163    /// # use datafusion_expr::{AggregateUDFImpl, AggregateUDF, Accumulator, function::{AccumulatorArgs, StateFieldsArgs}};
164    /// # use arrow::datatypes::Field;
165    /// #
166    /// # #[derive(Debug, Clone, PartialEq, Eq, Hash)]
167    /// # struct FirstValueUdf {
168    /// #     signature: Signature,
169    /// # }
170    /// #
171    /// # impl FirstValueUdf {
172    /// #     fn new() -> Self {
173    /// #         Self {
174    /// #             signature: Signature::any(1, Volatility::Immutable),
175    /// #         }
176    /// #     }
177    /// # }
178    /// #
179    /// # impl AggregateUDFImpl for FirstValueUdf {
180    /// #     fn name(&self) -> &str {
181    /// #         unimplemented!()
182    /// #     }
183    /// #
184    /// #     fn signature(&self) -> &Signature {
185    /// #         unimplemented!()
186    /// #     }
187    /// #
188    /// #     fn return_type(&self, args: &[DataType]) -> Result<DataType> {
189    /// #         unimplemented!()
190    /// #     }
191    /// #
192    /// #     fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
193    /// #         unimplemented!()
194    /// #         }
195    /// #
196    /// #     fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
197    /// #         unimplemented!()
198    /// #     }
199    /// #
200    /// #     fn documentation(&self) -> Option<&Documentation> {
201    /// #         unimplemented!()
202    /// #     }
203    /// # }
204    /// #
205    /// # let first_value = AggregateUDF::from(FirstValueUdf::new());
206    /// # let expr = first_value.call(vec![col("a")]);
207    /// #
208    /// # use datafusion_physical_expr::expressions::Column;
209    /// # use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
210    /// # use datafusion_physical_expr::aggregate::AggregateExprBuilder;
211    /// # use datafusion_physical_expr::expressions::PhysicalSortExpr;
212    /// # use datafusion_physical_expr::PhysicalSortRequirement;
213    /// #
214    /// fn build_aggregate_expr() -> Result<()> {
215    ///     let args = vec![Arc::new(Column::new("a", 0)) as Arc<dyn PhysicalExpr>];
216    ///     let order_by = vec![PhysicalSortExpr {
217    ///         expr: Arc::new(Column::new("x", 1)) as Arc<dyn PhysicalExpr>,
218    ///         options: Default::default(),
219    ///     }];
220    ///
221    ///     let first_value = AggregateUDF::from(FirstValueUdf::new());
222    ///
223    ///     let aggregate_expr = AggregateExprBuilder::new(
224    ///         Arc::new(first_value),
225    ///         args
226    ///     )
227    ///     .order_by(order_by)
228    ///     .alias("first_a_by_x")
229    ///     .ignore_nulls()
230    ///     .build()?;
231    ///
232    ///     Ok(())
233    /// }
234    /// ```
235    ///
236    /// This creates a physical expression equivalent to SQL:
237    /// `first_value(a ORDER BY x) IGNORE NULLS AS first_a_by_x`
238    pub fn build(self) -> Result<AggregateFunctionExpr> {
239        let Self {
240            fun,
241            args,
242            alias,
243            output_metadata,
244            human_display,
245            human_display_alias,
246            schema,
247            order_bys,
248            ignore_nulls,
249            is_distinct,
250            is_reversed,
251        } = self;
252        assert_or_internal_err!(!args.is_empty(), "args should not be empty");
253
254        // An order-insensitive aggregate ignores its ORDER BY, so drop it here.
255        // Otherwise drop sort keys that repeat an earlier one: a repeated key can
256        // never break a tie the earlier one left (`ORDER BY b ASC, b DESC` orders
257        // like `ORDER BY b ASC`), and accumulators build their ordering with
258        // `LexOrdering`, which drops such repeats. Everything derived from
259        // `order_bys` below, such as the ordering fields in the aggregate's
260        // state, then matches the sort keys the accumulators compare.
261        let order_bys = if fun.order_sensitivity().is_insensitive() {
262            vec![]
263        } else {
264            LexOrdering::new(order_bys)
265                .map(Vec::from)
266                .unwrap_or_default()
267        };
268
269        let ordering_types = order_bys
270            .iter()
271            .map(|e| e.expr.data_type(&schema))
272            .collect::<Result<Vec<_>>>()?;
273
274        let ordering_fields = utils::ordering_fields(&order_bys, &ordering_types);
275
276        let input_exprs_fields = args
277            .iter()
278            .map(|arg| arg.return_field(&schema))
279            .collect::<Result<Vec<_>>>()?;
280
281        check_arg_count(
282            fun.name(),
283            &input_exprs_fields,
284            &fun.signature().type_signature,
285        )?;
286
287        let mut return_field = fun.return_field(&input_exprs_fields)?;
288        if let Some(output_metadata) = output_metadata {
289            return_field = output_metadata.add_to_field_ref(return_field);
290        }
291        let Some(name) = alias else {
292            return internal_err!(
293                "AggregateExprBuilder::alias must be provided prior to calling build"
294            );
295        };
296
297        let human_display =
298            AggregateHumanDisplay::try_new(human_display, human_display_alias, &name)?;
299
300        let arg_fields = args
301            .iter()
302            .map(|e| e.return_field(schema.as_ref()))
303            .collect::<Result<Vec<_>>>()?;
304
305        Ok(AggregateFunctionExpr {
306            fun: Arc::unwrap_or_clone(fun),
307            args,
308            arg_fields,
309            return_field,
310            name,
311            human_display,
312            schema: Arc::unwrap_or_clone(schema),
313            order_bys,
314            ignore_nulls,
315            ordering_fields,
316            is_distinct,
317            input_fields: input_exprs_fields,
318            is_reversed,
319        })
320    }
321
322    pub fn alias(mut self, alias: impl Into<String>) -> Self {
323        self.alias = Some(alias.into());
324        self
325    }
326
327    fn output_metadata(mut self, metadata: Option<FieldMetadata>) -> Self {
328        self.output_metadata = metadata;
329        self
330    }
331
332    pub fn human_display(mut self, name: impl Into<String>) -> Self {
333        let name = name.into();
334        self.human_display = (!name.is_empty()).then_some(name);
335        if self.human_display.is_none() {
336            self.human_display_alias = None;
337        }
338        self
339    }
340
341    /// # Public Only for Internal Use:
342    ///
343    /// This is not a public API and is for internal use only; see [API policy] for details.
344    ///
345    /// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis
346    #[doc(hidden)]
347    pub fn human_display_alias(mut self, alias: impl Into<String>) -> Self {
348        let alias = alias.into();
349        self.human_display_alias = (!alias.is_empty()).then_some(alias);
350        self
351    }
352
353    pub fn schema(mut self, schema: SchemaRef) -> Self {
354        self.schema = schema;
355        self
356    }
357
358    pub fn order_by(mut self, order_bys: Vec<PhysicalSortExpr>) -> Self {
359        self.order_bys = order_bys;
360        self
361    }
362
363    pub fn reversed(mut self) -> Self {
364        self.is_reversed = true;
365        self
366    }
367
368    pub fn with_reversed(mut self, is_reversed: bool) -> Self {
369        self.is_reversed = is_reversed;
370        self
371    }
372
373    pub fn distinct(mut self) -> Self {
374        self.is_distinct = true;
375        self
376    }
377
378    pub fn with_distinct(mut self, is_distinct: bool) -> Self {
379        self.is_distinct = is_distinct;
380        self
381    }
382
383    pub fn ignore_nulls(mut self) -> Self {
384        self.ignore_nulls = true;
385        self
386    }
387
388    pub fn with_ignore_nulls(mut self, ignore_nulls: bool) -> Self {
389        self.ignore_nulls = ignore_nulls;
390        self
391    }
392}
393
394#[derive(Debug, Clone)]
395struct LoweredAggregateHumanDisplay {
396    expression: String,
397    alias: Option<String>,
398}
399
400/// Result of lowering a logical aggregate expression into physical aggregate
401/// planning pieces.
402#[derive(Debug, Clone)]
403pub struct LoweredAggregate {
404    /// Physical aggregate expression that can be used by an aggregate execution
405    /// plan.
406    pub aggregate: Arc<AggregateFunctionExpr>,
407    /// Optional physical filter expression for `FILTER (WHERE ...)`.
408    pub filter: Option<Arc<dyn PhysicalExpr>>,
409    /// Physical ordering expressions from aggregate `ORDER BY`.
410    pub order_bys: Vec<PhysicalSortExpr>,
411}
412
413/// Builder for converting a logical aggregate [`Expr`] into physical aggregate
414/// planning pieces.
415///
416/// This builder handles the logical-to-physical work needed for aggregate
417/// planning: unwrapping aggregate aliases, choosing the output name, preserving
418/// user-facing display text, lowering aggregate arguments, lowering the optional
419/// filter, and lowering aggregate `ORDER BY` expressions.
420pub struct LoweredAggregateBuilder<'a> {
421    expr: &'a Expr,
422    name: Option<String>,
423    human_display: Option<LoweredAggregateHumanDisplay>,
424    output_metadata: Option<FieldMetadata>,
425    preserve_alias_metadata: bool,
426    logical_input_schema: &'a DFSchema,
427    physical_input_schema: &'a Schema,
428    execution_props: &'a ExecutionProps,
429    planning_ctx: &'a PhysicalPlanningContext,
430}
431
432impl<'a> LoweredAggregateBuilder<'a> {
433    /// Create a builder for lowering `expr`.
434    ///
435    /// `logical_input_schema` is used to resolve logical expressions such as
436    /// columns, while `physical_input_schema` is the input schema used by the
437    /// physical aggregate expression. `planning_ctx` is used when creating
438    /// physical expressions that reference uncorrelated scalar subqueries.
439    /// Callers creating physical aggregates outside of physical planning should
440    /// pass `&PhysicalPlanningContext::default()`, in which case converting a
441    /// scalar-subquery expression returns a planning error.
442    pub fn new(
443        expr: &'a Expr,
444        logical_input_schema: &'a DFSchema,
445        physical_input_schema: &'a Schema,
446        execution_props: &'a ExecutionProps,
447        planning_ctx: &'a PhysicalPlanningContext,
448    ) -> Self {
449        Self {
450            expr,
451            name: None,
452            human_display: None,
453            output_metadata: None,
454            preserve_alias_metadata: true,
455            logical_input_schema,
456            physical_input_schema,
457            execution_props,
458            planning_ctx,
459        }
460    }
461
462    /// Override the output column name for the aggregate.
463    ///
464    /// If this is not set, the builder uses the alias from `expr` when present,
465    /// or derives the physical name from the aggregate expression.
466    pub fn with_name(mut self, name: impl Into<String>) -> Self {
467        self.name = Some(name.into());
468        self
469    }
470
471    /// Override the human-readable display text for the aggregate.
472    ///
473    /// This is useful when a caller has already computed the exact display text
474    /// it wants to preserve. When this override is used, aliases with metadata
475    /// are still unwrapped for planning, but alias metadata is not copied to the
476    /// aggregate output field.
477    pub fn with_human_display(mut self, human_display: impl Into<String>) -> Self {
478        self.human_display = Some(LoweredAggregateHumanDisplay {
479            expression: human_display.into(),
480            alias: None,
481        });
482        self.preserve_alias_metadata = false;
483        self
484    }
485
486    /// Lower the logical aggregate expression into physical aggregate pieces.
487    pub fn build(self) -> Result<LoweredAggregate> {
488        let Self {
489            expr,
490            name,
491            human_display,
492            output_metadata,
493            preserve_alias_metadata,
494            logical_input_schema,
495            physical_input_schema,
496            execution_props,
497            planning_ctx,
498        } = self;
499
500        let (name, human_display, output_metadata, expr) = lower_aggregate_display(
501            expr,
502            name,
503            human_display,
504            output_metadata,
505            preserve_alias_metadata,
506        );
507
508        let Expr::AggregateFunction(AggregateFunction {
509            func,
510            params:
511                AggregateFunctionParams {
512                    args,
513                    distinct,
514                    filter,
515                    order_by,
516                    null_treatment,
517                },
518        }) = &expr
519        else {
520            return internal_err!("Invalid aggregate expression '{expr:?}'");
521        };
522
523        let name = if let Some(name) = name {
524            name
525        } else {
526            physical_name(&expr)?
527        };
528
529        let physical_args = create_physical_exprs(
530            args,
531            logical_input_schema,
532            execution_props,
533            planning_ctx,
534        )?;
535        let filter = filter
536            .as_ref()
537            .map(|filter| {
538                create_physical_expr(
539                    filter,
540                    logical_input_schema,
541                    execution_props,
542                    planning_ctx,
543                )
544            })
545            .transpose()?;
546        let order_bys = create_physical_sort_exprs(
547            order_by,
548            logical_input_schema,
549            execution_props,
550            planning_ctx,
551        )?;
552        let ignore_nulls = null_treatment.unwrap_or(NullTreatment::RespectNulls)
553            == NullTreatment::IgnoreNulls;
554
555        let mut builder = AggregateExprBuilder::new(func.to_owned(), physical_args)
556            .order_by(order_bys.clone())
557            .schema(Arc::new(physical_input_schema.to_owned()))
558            .alias(name)
559            .output_metadata(output_metadata)
560            .with_ignore_nulls(ignore_nulls)
561            .with_distinct(*distinct);
562
563        if let Some(human_display) = human_display {
564            builder = builder.human_display(human_display.expression);
565            if let Some(alias) = human_display.alias {
566                builder = builder.human_display_alias(alias);
567            }
568        }
569
570        Ok(LoweredAggregate {
571            aggregate: Arc::new(builder.build()?),
572            filter,
573            order_bys,
574        })
575    }
576}
577
578fn lower_aggregate_display(
579    expr: &Expr,
580    name: Option<String>,
581    human_display: Option<LoweredAggregateHumanDisplay>,
582    output_metadata: Option<FieldMetadata>,
583    preserve_alias_metadata: bool,
584) -> (
585    Option<String>,
586    Option<LoweredAggregateHumanDisplay>,
587    Option<FieldMetadata>,
588    Expr,
589) {
590    let mut expr = expr.clone();
591    let mut alias_name = None;
592    let mut alias_metadata = None;
593    while let Expr::Alias(alias) = expr {
594        if alias_name.is_none() {
595            alias_name = Some(alias.name);
596            alias_metadata = alias.metadata;
597        }
598        expr = *alias.expr;
599    }
600
601    let output_metadata = if preserve_alias_metadata {
602        output_metadata.or(alias_metadata)
603    } else {
604        output_metadata
605    };
606
607    if human_display.is_some() {
608        return (name.or(alias_name), human_display, output_metadata, expr);
609    }
610
611    match &expr {
612        Expr::AggregateFunction(_) => {
613            if let Some(alias_name) = alias_name {
614                let name = name.unwrap_or(alias_name);
615                let expression = expr.human_display().to_string();
616                let human_display = if expression.is_empty() || expression == name {
617                    LoweredAggregateHumanDisplay {
618                        expression: name.clone(),
619                        alias: None,
620                    }
621                } else {
622                    LoweredAggregateHumanDisplay {
623                        expression,
624                        alias: Some(name.clone()),
625                    }
626                };
627
628                return (Some(name), Some(human_display), output_metadata, expr);
629            }
630
631            let name = name.unwrap_or_else(|| expr.schema_name().to_string());
632            let human_display = LoweredAggregateHumanDisplay {
633                expression: expr.human_display().to_string(),
634                alias: None,
635            };
636
637            (Some(name), Some(human_display), output_metadata, expr)
638        }
639        _ => (name.or(alias_name), None, output_metadata, expr),
640    }
641}
642
643/// Physical aggregate expression of a UDAF.
644///
645/// Instances are constructed via [`AggregateExprBuilder`].
646#[derive(Debug, Clone)]
647pub struct AggregateFunctionExpr {
648    fun: AggregateUDF,
649    args: Vec<Arc<dyn PhysicalExpr>>,
650    /// Fields corresponding to args (same order & length)
651    arg_fields: Vec<FieldRef>,
652    /// Output / return field of this aggregate
653    return_field: FieldRef,
654    /// Output column name that this expression creates
655    name: String,
656    /// Simplified name for `tree` explain.
657    human_display: Option<AggregateHumanDisplay>,
658    schema: Schema,
659    // The physical order by expressions
660    order_bys: Vec<PhysicalSortExpr>,
661    // Whether to ignore null values
662    ignore_nulls: bool,
663    // fields used for order sensitive aggregation functions
664    ordering_fields: Vec<FieldRef>,
665    is_distinct: bool,
666    is_reversed: bool,
667    input_fields: Vec<FieldRef>,
668}
669
670impl AggregateFunctionExpr {
671    /// Return the `AggregateUDF` used by this `AggregateFunctionExpr`
672    pub fn fun(&self) -> &AggregateUDF {
673        &self.fun
674    }
675
676    /// expressions that are passed to the Accumulator.
677    /// Single-column aggregations such as `sum` return a single value, others (e.g. `cov`) return many.
678    pub fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
679        self.args.clone()
680    }
681
682    /// Human readable name such as `"MIN(c2)"`.
683    pub fn name(&self) -> &str {
684        &self.name
685    }
686
687    /// Simplified name for `tree` explain.
688    pub fn human_display(&self) -> Option<&str> {
689        self.human_display
690            .as_ref()
691            .map(AggregateHumanDisplay::expression)
692    }
693
694    /// # Public Only for Internal Use:
695    ///
696    /// This is not a public API and is for internal use only; see [API policy] for details.
697    ///
698    /// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis
699    #[doc(hidden)]
700    pub fn human_display_alias(&self) -> Option<&str> {
701        self.human_display
702            .as_ref()
703            .and_then(AggregateHumanDisplay::alias)
704    }
705
706    fn return_field_metadata(&self) -> Option<FieldMetadata> {
707        let metadata = FieldMetadata::from(self.return_field.as_ref());
708        (!metadata.is_empty()).then_some(metadata)
709    }
710
711    /// Return if the aggregation is distinct
712    pub fn is_distinct(&self) -> bool {
713        self.is_distinct
714    }
715
716    /// Return if the aggregation ignores nulls
717    pub fn ignore_nulls(&self) -> bool {
718        self.ignore_nulls
719    }
720
721    /// Return if the aggregation is reversed
722    pub fn is_reversed(&self) -> bool {
723        self.is_reversed
724    }
725
726    /// Return if the aggregation is nullable
727    pub fn is_nullable(&self) -> bool {
728        self.return_field.is_nullable()
729    }
730
731    /// the field of the final result of this aggregation.
732    pub fn field(&self) -> FieldRef {
733        self.return_field
734            .as_ref()
735            .clone()
736            .with_name(&self.name)
737            .into()
738    }
739
740    /// the accumulator used to accumulate values from the expressions.
741    /// the accumulator expects the same number of arguments as `expressions` and must
742    /// return states with the same description as `state_fields`
743    pub fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
744        let acc_args = AccumulatorArgs {
745            return_field: Arc::clone(&self.return_field),
746            schema: &self.schema,
747            expr_fields: &self.arg_fields,
748            ignore_nulls: self.ignore_nulls,
749            order_bys: self.order_bys.as_ref(),
750            is_distinct: self.is_distinct,
751            name: &self.name,
752            is_reversed: self.is_reversed,
753            exprs: &self.args,
754        };
755
756        self.fun.accumulator(acc_args)
757    }
758
759    /// Creates an accumulator and supplies optional aggregate-owned metrics.
760    pub fn create_accumulator_with_metrics(
761        &self,
762        metrics: Arc<dyn AggregateMetrics>,
763    ) -> Result<Box<dyn Accumulator>> {
764        let mut accumulator = self.create_accumulator()?;
765        accumulator.set_metrics(metrics);
766        Ok(accumulator)
767    }
768
769    /// the field of the final result of this aggregation.
770    pub fn state_fields(&self) -> Result<Vec<FieldRef>> {
771        let args = StateFieldsArgs {
772            name: &self.name,
773            input_fields: &self.input_fields,
774            return_field: Arc::clone(&self.return_field),
775            ordering_fields: &self.ordering_fields,
776            is_distinct: self.is_distinct,
777        };
778
779        self.fun.state_fields(args)
780    }
781
782    /// Returns the ORDER BY expressions for the aggregate function.
783    pub fn order_bys(&self) -> &[PhysicalSortExpr] {
784        &self.order_bys
785    }
786
787    /// Indicates whether aggregator can produce the correct result with any
788    /// arbitrary input ordering. By default, we assume that aggregate expressions
789    /// are order insensitive.
790    pub fn order_sensitivity(&self) -> AggregateOrderSensitivity {
791        if self.order_bys.is_empty() {
792            AggregateOrderSensitivity::Insensitive
793        } else {
794            // If there is an ORDER BY clause, use the sensitivity of the implementation:
795            self.fun.order_sensitivity()
796        }
797    }
798
799    /// Sets the indicator whether ordering requirements of the aggregator is
800    /// satisfied by its input. If this is not the case, aggregators with order
801    /// sensitivity `AggregateOrderSensitivity::Beneficial` can still produce
802    /// the correct result with possibly more work internally.
803    ///
804    /// # Returns
805    ///
806    /// Returns `Ok(Some(updated_expr))` if the process completes successfully.
807    /// If the expression can benefit from existing input ordering, but does
808    /// not implement the method, returns an error. Order insensitive and hard
809    /// requirement aggregators return `Ok(None)`.
810    pub fn with_beneficial_ordering(
811        self: Arc<Self>,
812        beneficial_ordering: bool,
813    ) -> Result<Option<AggregateFunctionExpr>> {
814        let Some(updated_fn) = self
815            .fun
816            .clone()
817            .with_beneficial_ordering(beneficial_ordering)?
818        else {
819            return Ok(None);
820        };
821
822        let mut builder =
823            AggregateExprBuilder::new(Arc::new(updated_fn), self.args.to_vec())
824                .order_by(self.order_bys.clone())
825                .schema(Arc::new(self.schema.clone()))
826                .alias(self.name().to_string())
827                .output_metadata(self.return_field_metadata())
828                .with_ignore_nulls(self.ignore_nulls)
829                .with_distinct(self.is_distinct)
830                .with_reversed(self.is_reversed);
831        if let Some(human_display) = self.human_display() {
832            builder = builder.human_display(human_display);
833        }
834        if let Some(alias) = self.human_display_alias() {
835            builder = builder.human_display_alias(alias);
836        }
837        builder.build().map(Some)
838    }
839
840    /// Creates accumulator implementation that supports retract
841    pub fn create_sliding_accumulator(&self) -> Result<Box<dyn Accumulator>> {
842        let args = AccumulatorArgs {
843            return_field: Arc::clone(&self.return_field),
844            schema: &self.schema,
845            expr_fields: &self.arg_fields,
846            ignore_nulls: self.ignore_nulls,
847            order_bys: self.order_bys.as_ref(),
848            is_distinct: self.is_distinct,
849            name: &self.name,
850            is_reversed: self.is_reversed,
851            exprs: &self.args,
852        };
853
854        let accumulator = self.fun.create_sliding_accumulator(args)?;
855
856        // Accumulators that have window frame startings different
857        // than `UNBOUNDED PRECEDING`, such as `1 PRECEDING`, need to
858        // implement retract_batch method in order to run correctly
859        // currently in DataFusion.
860        //
861        // If this `retract_batches` is not present, there is no way
862        // to calculate result correctly. For example, the query
863        //
864        // ```sql
865        // SELECT
866        //  SUM(a) OVER(ORDER BY a ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS sum_a
867        // FROM
868        //  t
869        // ```
870        //
871        // 1. First sum value will be the sum of rows between `[0, 1)`,
872        //
873        // 2. Second sum value will be the sum of rows between `[0, 2)`
874        //
875        // 3. Third sum value will be the sum of rows between `[1, 3)`, etc.
876        //
877        // Since the accumulator keeps the running sum:
878        //
879        // 1. First sum we add to the state sum value between `[0, 1)`
880        //
881        // 2. Second sum we add to the state sum value between `[1, 2)`
882        // (`[0, 1)` is already in the state sum, hence running sum will
883        // cover `[0, 2)` range)
884        //
885        // 3. Third sum we add to the state sum value between `[2, 3)`
886        // (`[0, 2)` is already in the state sum).  Also we need to
887        // retract values between `[0, 1)` by this way we can obtain sum
888        // between [1, 3) which is indeed the appropriate range.
889        //
890        // When we use `UNBOUNDED PRECEDING` in the query starting
891        // index will always be 0 for the desired range, and hence the
892        // `retract_batch` method will not be called. In this case
893        // having retract_batch is not a requirement.
894        //
895        // This approach is a bit different than window function
896        // approach. In window function (when they use a window frame)
897        // they get all the desired range during evaluation.
898        if !accumulator.supports_retract_batch() {
899            return not_impl_err!(
900                "Aggregate can not be used as a sliding accumulator because \
901                     `retract_batch` is not implemented: {}",
902                self.name
903            );
904        }
905        Ok(accumulator)
906    }
907
908    /// If the aggregate expression has a specialized
909    /// [`GroupsAccumulator`] implementation. If this returns true,
910    /// `[Self::create_groups_accumulator`] will be called.
911    pub fn groups_accumulator_supported(&self) -> bool {
912        let args = AccumulatorArgs {
913            return_field: Arc::clone(&self.return_field),
914            schema: &self.schema,
915            expr_fields: &self.arg_fields,
916            ignore_nulls: self.ignore_nulls,
917            order_bys: self.order_bys.as_ref(),
918            is_distinct: self.is_distinct,
919            name: &self.name,
920            is_reversed: self.is_reversed,
921            exprs: &self.args,
922        };
923        self.fun.groups_accumulator_supported(args)
924    }
925
926    /// Return a specialized [`GroupsAccumulator`] that manages state
927    /// for all groups.
928    ///
929    /// For maximum performance, a [`GroupsAccumulator`] should be
930    /// implemented in addition to [`Accumulator`].
931    pub fn create_groups_accumulator(&self) -> Result<Box<dyn GroupsAccumulator>> {
932        let args = AccumulatorArgs {
933            return_field: Arc::clone(&self.return_field),
934            schema: &self.schema,
935            expr_fields: &self.arg_fields,
936            ignore_nulls: self.ignore_nulls,
937            order_bys: self.order_bys.as_ref(),
938            is_distinct: self.is_distinct,
939            name: &self.name,
940            is_reversed: self.is_reversed,
941            exprs: &self.args,
942        };
943        self.fun.create_groups_accumulator(args)
944    }
945
946    /// Creates a groups accumulator and supplies optional aggregate-owned metrics.
947    pub fn create_groups_accumulator_with_metrics(
948        &self,
949        metrics: Arc<dyn AggregateMetrics>,
950    ) -> Result<Box<dyn GroupsAccumulator>> {
951        let mut accumulator = self.create_groups_accumulator()?;
952        accumulator.set_metrics(metrics);
953        Ok(accumulator)
954    }
955
956    /// Construct an expression that calculates the aggregate in reverse.
957    /// Typically the "reverse" expression is itself (e.g. SUM, COUNT).
958    /// For aggregates that do not support calculation in reverse,
959    /// returns None (which is the default value).
960    pub fn reverse_expr(&self) -> Option<AggregateFunctionExpr> {
961        self.reverse_expr_inner(false)
962    }
963
964    /// Same as [`Self::reverse_expr`], but the output `name` is always carried
965    /// over unchanged.
966    ///
967    /// Window execs derive their output schema from `WindowExpr::field()`, which
968    /// for aggregate-backed window expressions is this expression's `name`. If
969    /// reversal renamed it, the rebuilt window exec would expose a differently
970    /// named column while parent plan nodes still reference the old one. This
971    /// mirrors `WindowUDFExpr::reverse_expr`, which preserves its name for the
972    /// same reason. `AggregateExec`, by contrast, pins its schema at
973    /// construction, so it can use [`Self::reverse_expr`] and let the name
974    /// reflect the function actually being evaluated.
975    pub(crate) fn reverse_expr_preserving_name(&self) -> Option<AggregateFunctionExpr> {
976        self.reverse_expr_inner(true)
977    }
978
979    fn reverse_expr_inner(&self, preserve_name: bool) -> Option<AggregateFunctionExpr> {
980        match self.fun.reverse_udf() {
981            ReversedUDAF::NotSupported => None,
982            ReversedUDAF::Identical => Some(self.clone()),
983            ReversedUDAF::Reversed(reverse_udf) => {
984                let keep_name = preserve_name || self.human_display_alias().is_some();
985                let mut name = self.name().to_string();
986                let mut human_display = self.human_display.clone();
987                // Reversing display follows two paths:
988                // - aliased display (or an explicit request to keep the name) keeps
989                //   the output `name` unchanged and rewrites only the lowered
990                //   expression in `human_display`.
991                // - non-aliased display rewrites the canonical `name`, and rewrites
992                //   `human_display` only when present.
993                // If the function is changed, we need to reverse order_by clause as well
994                // i.e. First(a order by b asc null first) -> Last(a order by b desc null last)
995                if !keep_name && self.fun().name() != reverse_udf.name() {
996                    replace_order_by_clause(&mut name);
997                }
998                if !keep_name {
999                    replace_fn_name_clause(
1000                        &mut name,
1001                        self.fun.name(),
1002                        reverse_udf.name(),
1003                    );
1004                }
1005
1006                if let Some(human_display) = human_display.as_mut() {
1007                    if self.fun().name() != reverse_udf.name() {
1008                        replace_order_by_clause(&mut human_display.expression);
1009                    }
1010                    replace_fn_name_clause(
1011                        &mut human_display.expression,
1012                        self.fun.name(),
1013                        reverse_udf.name(),
1014                    );
1015                }
1016
1017                let mut builder =
1018                    AggregateExprBuilder::new(reverse_udf, self.args.to_vec())
1019                        .order_by(self.order_bys.iter().map(|e| e.reverse()).collect())
1020                        .schema(Arc::new(self.schema.clone()))
1021                        .alias(name)
1022                        .output_metadata(self.return_field_metadata())
1023                        .with_ignore_nulls(self.ignore_nulls)
1024                        .with_distinct(self.is_distinct)
1025                        .with_reversed(!self.is_reversed);
1026                if let Some(human_display) = human_display {
1027                    builder = builder.human_display(human_display.expression);
1028                    if let Some(alias) = human_display.alias {
1029                        builder = builder.human_display_alias(alias);
1030                    }
1031                }
1032                builder.build().ok()
1033            }
1034        }
1035    }
1036
1037    /// Returns all expressions used in the [`AggregateFunctionExpr`].
1038    /// These expressions are  (1)function arguments, (2) order by expressions.
1039    pub fn all_expressions(&self) -> AggregatePhysicalExpressions {
1040        let args = self.expressions();
1041        let order_by_exprs = self
1042            .order_bys()
1043            .iter()
1044            .map(|sort_expr| Arc::clone(&sort_expr.expr))
1045            .collect();
1046        AggregatePhysicalExpressions {
1047            args,
1048            order_by_exprs,
1049        }
1050    }
1051
1052    /// Rewrites [`AggregateFunctionExpr`], with new expressions given. The argument should be consistent
1053    /// with the return value of the [`AggregateFunctionExpr::all_expressions`] method.
1054    /// Returns `Some(Arc<dyn AggregateExpr>)` if re-write is supported, otherwise returns `None`.
1055    pub fn with_new_expressions(
1056        &self,
1057        args: Vec<Arc<dyn PhysicalExpr>>,
1058        order_by_exprs: Vec<Arc<dyn PhysicalExpr>>,
1059    ) -> Option<AggregateFunctionExpr> {
1060        if args.len() != self.args.len() || order_by_exprs.len() != self.order_bys.len() {
1061            return None;
1062        }
1063
1064        let new_order_bys = self
1065            .order_bys
1066            .iter()
1067            .zip(order_by_exprs)
1068            .map(|(req, new_expr)| PhysicalSortExpr {
1069                expr: new_expr,
1070                options: req.options,
1071            })
1072            .collect();
1073
1074        Some(AggregateFunctionExpr {
1075            fun: self.fun.clone(),
1076            args,
1077            // TODO: need to align arg_fields here with new args
1078            //       https://github.com/apache/datafusion/issues/18149
1079            arg_fields: self.arg_fields.clone(),
1080            return_field: Arc::clone(&self.return_field),
1081            name: self.name.clone(),
1082            // TODO: Human name should be updated after re-write to not mislead
1083            human_display: self.human_display.clone(),
1084            schema: self.schema.clone(),
1085            order_bys: new_order_bys,
1086            ignore_nulls: self.ignore_nulls,
1087            ordering_fields: self.ordering_fields.clone(),
1088            is_distinct: self.is_distinct,
1089            is_reversed: false,
1090            input_fields: self.input_fields.clone(),
1091        })
1092    }
1093
1094    /// If this function is max, return (output_field, true)
1095    /// if the function is min, return (output_field, false)
1096    /// otherwise return None (the default)
1097    ///
1098    /// output_field is the name of the column produced by this aggregate
1099    ///
1100    /// Note: this is used to use special aggregate implementations in certain conditions
1101    pub fn get_minmax_desc(&self) -> Option<(FieldRef, bool)> {
1102        self.fun.is_descending().map(|flag| (self.field(), flag))
1103    }
1104
1105    /// Returns default value of the function given the input is Null
1106    /// Most of the aggregate function return Null if input is Null,
1107    /// while `count` returns 0 if input is Null
1108    pub fn default_value(&self, data_type: &DataType) -> Result<ScalarValue> {
1109        self.fun.default_value(data_type)
1110    }
1111
1112    /// Indicates whether the aggregation function is monotonic as a set
1113    /// function. See [`SetMonotonicity`] for details.
1114    pub fn set_monotonicity(&self) -> SetMonotonicity {
1115        let field = self.field();
1116        let data_type = field.data_type();
1117        self.fun.inner().set_monotonicity(data_type)
1118    }
1119
1120    /// Returns `PhysicalSortExpr` based on the set monotonicity of the function.
1121    pub fn get_result_ordering(&self, aggr_func_idx: usize) -> Option<PhysicalSortExpr> {
1122        // If the aggregate expressions are set-monotonic, the output data is
1123        // naturally ordered with it per group or partition.
1124        let monotonicity = self.set_monotonicity();
1125        if monotonicity == SetMonotonicity::NotMonotonic {
1126            return None;
1127        }
1128        let expr = Arc::new(Column::new(self.name(), aggr_func_idx));
1129        let options =
1130            SortOptions::new(monotonicity == SetMonotonicity::Decreasing, false);
1131        Some(PhysicalSortExpr { expr, options })
1132    }
1133}
1134
1135/// Stores the physical expressions used inside the `AggregateExpr`.
1136pub struct AggregatePhysicalExpressions {
1137    /// Aggregate function arguments
1138    pub args: Vec<Arc<dyn PhysicalExpr>>,
1139    /// Order by expressions
1140    pub order_by_exprs: Vec<Arc<dyn PhysicalExpr>>,
1141}
1142
1143impl PartialEq for AggregateFunctionExpr {
1144    fn eq(&self, other: &Self) -> bool {
1145        self.name == other.name
1146            && self.return_field == other.return_field
1147            && self.fun == other.fun
1148            && self.args.len() == other.args.len()
1149            && self
1150                .args
1151                .iter()
1152                .zip(other.args.iter())
1153                .all(|(this_arg, other_arg)| this_arg.eq(other_arg))
1154    }
1155}
1156
1157fn replace_order_by_clause(order_by: &mut String) {
1158    let suffixes = [
1159        (" DESC NULLS FIRST]", " ASC NULLS LAST]"),
1160        (" ASC NULLS FIRST]", " DESC NULLS LAST]"),
1161        (" DESC NULLS LAST]", " ASC NULLS FIRST]"),
1162        (" ASC NULLS LAST]", " DESC NULLS FIRST]"),
1163    ];
1164
1165    if let Some(start) = order_by.find("ORDER BY [")
1166        && let Some(end) = order_by[start..].find(']')
1167    {
1168        let order_by_start = start + 9;
1169        let order_by_end = start + end;
1170
1171        let column_order = &order_by[order_by_start..=order_by_end];
1172        for (suffix, replacement) in suffixes {
1173            if column_order.ends_with(suffix) {
1174                let new_order = column_order.replace(suffix, replacement);
1175                order_by.replace_range(order_by_start..=order_by_end, &new_order);
1176                break;
1177            }
1178        }
1179    }
1180}
1181
1182fn replace_fn_name_clause(aggr_name: &mut String, fn_name_old: &str, fn_name_new: &str) {
1183    if let Some(rest) = aggr_name.strip_prefix(fn_name_old) {
1184        *aggr_name = format!("{fn_name_new}{rest}");
1185    }
1186}
1187
1188#[cfg(test)]
1189mod tests {
1190    use super::*;
1191
1192    use std::collections::HashMap;
1193
1194    use arrow::datatypes::Field;
1195    use datafusion_common::metadata::FieldMetadata;
1196    use datafusion_expr::{
1197        AggregateUDFImpl, Signature, Volatility, col, test::function_stub::sum,
1198    };
1199
1200    fn aggregate_test_schema() -> Result<(Schema, DFSchema)> {
1201        let schema = Schema::new(vec![Field::new("column1", DataType::Int64, true)]);
1202        let logical_schema = DFSchema::try_from(schema.clone())?;
1203        Ok((schema, logical_schema))
1204    }
1205
1206    fn test_metadata() -> FieldMetadata {
1207        FieldMetadata::from(HashMap::from([(
1208            "some_key".to_string(),
1209            "some_value".to_string(),
1210        )]))
1211    }
1212
1213    fn aggregate_alias_with_metadata() -> Expr {
1214        sum(col("column1")).alias_with_metadata("agg", Some(test_metadata()))
1215    }
1216
1217    #[test]
1218    fn lowered_aggregate_builder_unwraps_alias_with_metadata() -> Result<()> {
1219        let (schema, logical_schema) = aggregate_test_schema()?;
1220        let expr = aggregate_alias_with_metadata();
1221
1222        let lowered = LoweredAggregateBuilder::new(
1223            &expr,
1224            &logical_schema,
1225            &schema,
1226            &ExecutionProps::new(),
1227            &PhysicalPlanningContext::default(),
1228        )
1229        .build()?;
1230
1231        assert_eq!(lowered.aggregate.name(), "agg");
1232        assert_eq!(lowered.aggregate.human_display_alias(), Some("agg"));
1233        assert_eq!(
1234            lowered.aggregate.field().metadata().get("some_key"),
1235            Some(&"some_value".to_string())
1236        );
1237
1238        Ok(())
1239    }
1240
1241    #[test]
1242    fn lowered_aggregate_builder_display_override_skips_alias_metadata() -> Result<()> {
1243        let (schema, logical_schema) = aggregate_test_schema()?;
1244        let expr = aggregate_alias_with_metadata();
1245
1246        let lowered = LoweredAggregateBuilder::new(
1247            &expr,
1248            &logical_schema,
1249            &schema,
1250            &ExecutionProps::new(),
1251            &PhysicalPlanningContext::default(),
1252        )
1253        .with_human_display(expr.human_display().to_string())
1254        .build()?;
1255
1256        assert_eq!(lowered.aggregate.name(), "agg");
1257        assert_eq!(lowered.aggregate.human_display_alias(), None);
1258        assert!(
1259            lowered
1260                .aggregate
1261                .field()
1262                .metadata()
1263                .get("some_key")
1264                .is_none()
1265        );
1266
1267        Ok(())
1268    }
1269
1270    /// An aggregate that uses the default `AggregateUDFImpl::state_fields`,
1271    /// which appends the ordering fields to the state.
1272    #[derive(Debug, PartialEq, Eq, Hash)]
1273    struct DefaultStateUdaf {
1274        signature: Signature,
1275        order_insensitive: bool,
1276    }
1277
1278    impl DefaultStateUdaf {
1279        fn new(order_insensitive: bool) -> Self {
1280            Self {
1281                signature: Signature::any(1, Volatility::Immutable),
1282                order_insensitive,
1283            }
1284        }
1285    }
1286
1287    impl AggregateUDFImpl for DefaultStateUdaf {
1288        fn name(&self) -> &str {
1289            "default_state_udaf"
1290        }
1291
1292        fn signature(&self) -> &Signature {
1293            &self.signature
1294        }
1295
1296        fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
1297            Ok(arg_types[0].clone())
1298        }
1299
1300        /// Always fails, reporting how many ORDER BY expressions it was given.
1301        fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
1302            not_impl_err!("accumulator with {} order_bys", acc_args.order_bys.len())
1303        }
1304
1305        fn order_sensitivity(&self) -> AggregateOrderSensitivity {
1306            if self.order_insensitive {
1307                AggregateOrderSensitivity::Insensitive
1308            } else {
1309                AggregateOrderSensitivity::HardRequirement
1310            }
1311        }
1312    }
1313
1314    /// Builds `default_state_udaf(v ORDER BY k)`.
1315    fn build_with_order_by(order_insensitive: bool) -> Result<AggregateFunctionExpr> {
1316        let schema = Arc::new(Schema::new(vec![
1317            Field::new("v", DataType::Int64, true),
1318            Field::new("k", DataType::Int64, true),
1319        ]));
1320        let fun = AggregateUDF::from(DefaultStateUdaf::new(order_insensitive));
1321        AggregateExprBuilder::new(Arc::new(fun), vec![Arc::new(Column::new("v", 0))])
1322            .order_by(vec![PhysicalSortExpr {
1323                expr: Arc::new(Column::new("k", 1)),
1324                options: SortOptions::default(),
1325            }])
1326            .schema(schema)
1327            .alias("default_state_udaf(v) ORDER BY [k ASC NULLS LAST]")
1328            .build()
1329    }
1330
1331    #[test]
1332    fn order_insensitive_aggregate_discards_order_by() -> Result<()> {
1333        let expr = build_with_order_by(true)?;
1334        assert!(expr.order_bys().is_empty());
1335        assert!(expr.all_expressions().order_by_exprs.is_empty());
1336        // Only the value: the default `state_fields` has no ordering fields to append
1337        assert_eq!(expr.state_fields()?.len(), 1);
1338        let err = expr.create_accumulator().unwrap_err();
1339        assert!(err.message().contains("accumulator with 0 order_bys"));
1340
1341        // Rewriting the expressions does not bring the ORDER BY back
1342        let rewritten = expr
1343            .with_new_expressions(expr.expressions(), vec![])
1344            .expect("rewrite is supported");
1345        assert!(rewritten.order_bys().is_empty());
1346        assert_eq!(rewritten.state_fields()?.len(), 1);
1347
1348        Ok(())
1349    }
1350
1351    #[test]
1352    fn order_sensitive_aggregate_keeps_order_by() -> Result<()> {
1353        let expr = build_with_order_by(false)?;
1354        assert_eq!(expr.order_bys().len(), 1);
1355        assert_eq!(expr.all_expressions().order_by_exprs.len(), 1);
1356        // The value, followed by the ordering field
1357        assert_eq!(expr.state_fields()?.len(), 2);
1358        let err = expr.create_accumulator().unwrap_err();
1359        assert!(err.message().contains("accumulator with 1 order_bys"));
1360
1361        Ok(())
1362    }
1363}