Apache DataFusion SQL Query Engine
[bug]: Fix multi partition wrong column requirement bug (#7129)
Mustafa Akure39b5ca32f15
diff --git a/datafusion/core/src/physical_plan/aggregates/mod.rs b/datafusion/core/src/physical_plan/aggregates/mod.rsindex f35b186f08..ac04be0c33 100644--- a/datafusion/core/src/physical_plan/aggregates/mod.rs+++ b/datafusion/core/src/physical_plan/aggregates/mod.rs@@ -25,6 +25,7 @@ use crate::physical_plan::{DisplayFormatType, Distribution, EquivalenceProperties, ExecutionPlan, Partitioning,SendableRecordBatchStream, Statistics,};+use arrow::array::ArrayRef;use arrow::datatypes::{Field, Schema, SchemaRef};use arrow::record_batch::RecordBatch;@@ -40,6 +41,7 @@ use datafusion_physical_expr::{AggregateExpr, LexOrdering, LexOrderingReq, OrderingEquivalenceProperties,PhysicalExpr, PhysicalSortExpr, PhysicalSortRequirement,};+use std::any::Any;use std::collections::HashMap;use std::sync::Arc;@@ -84,6 +86,20 @@ pub enum AggregateMode {SinglePartitioned,}+impl AggregateMode {+ /// Checks whether this aggregation step describes a "first stage" calculation.+ /// In other words, its input is not another aggregation result and the+ /// `merge_batch` method will not be called for these modes.+ fn is_first_stage(&self) -> bool {+ match self {+ AggregateMode::Partial+ | AggregateMode::Single+ | AggregateMode::SinglePartitioned => true,+ AggregateMode::Final | AggregateMode::FinalPartitioned => false,+ }+ }+}+/// Group By expression modes////// `PartiallyOrdered` and `FullyOrdered` are used to reason about@@ -95,9 +111,6 @@ pub enum AggregateMode {/// previous combinations are guaranteed never to appear again#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum GroupByOrderMode {- /// The input is not (known to be) ordered by any of the- /// expressions in the GROUP BY clause.- None,/// The input is known to be ordered by a preset (prefix but/// possibly reordered) of the expressions in the `GROUP BY` clause.///@@ -475,13 +488,13 @@ fn calc_required_input_ordering(};for (is_reverse, aggregator_requirement) in aggregator_requirements.into_iter() {if let Some(AggregationOrdering {- ordering,// If the mode is FullyOrdered or PartiallyOrdered (i.e. we are// running with bounded memory, without breaking the pipeline),// then we append the aggregator ordering requirement to the existing// ordering. This way, we can still run with bounded memory.mode: GroupByOrderMode::FullyOrdered | GroupByOrderMode::PartiallyOrdered,order_indices,+ ..}) = aggregation_ordering{// Get the section of the input ordering that enables us to run in@@ -495,32 +508,17 @@ fn calc_required_input_ordering(let mut requirement =PhysicalSortRequirement::from_sort_exprs(requirement_prefix.iter());for req in aggregator_requirement {- if requirement.iter().all(|item| req.expr.ne(&item.expr)) {- requirement.push(req.clone());- }- // In partial mode, append required ordering of the aggregator to the output ordering.- // In case of multiple partitions, this enables us to reduce partitions correctly.- if matches!(mode, AggregateMode::Partial)- && ordering.iter().all(|item| req.expr.ne(&item.expr))+ // Final and FinalPartitioned modes don't enforce ordering+ // requirements since order-sensitive aggregators handle such+ // requirements during merging.+ if mode.is_first_stage()+ && requirement.iter().all(|item| req.expr.ne(&item.expr)){- ordering.push(req.into());+ requirement.push(req);}}required_input_ordering = requirement;- } else {- // If there was no pre-existing output ordering, the output ordering is simply the required- // ordering of the aggregator in partial mode.- if matches!(mode, AggregateMode::Partial)- && !aggregator_requirement.is_empty()- {- *aggregation_ordering = Some(AggregationOrdering {- mode: GroupByOrderMode::None,- order_indices: vec![],- ordering: PhysicalSortRequirement::to_sort_exprs(- aggregator_requirement.clone(),- ),- });- }+ } else if mode.is_first_stage() {required_input_ordering = aggregator_requirement;}// Keep track of the direction from which required_input_ordering is constructed:@@ -596,12 +594,16 @@ impl AggregateExec {.iter().zip(order_by_expr.into_iter()).map(|(aggr_expr, fn_reqs)| {- // If aggregation function is ordering sensitive, keep ordering requirement as is; otherwise ignore requirement- if is_order_sensitive(aggr_expr) {- fn_reqs- } else {- None- }+ // If the aggregation function is order-sensitive and we are+ // performing a "first stage" calculation, keep the ordering+ // requirement as is; otherwise ignore the ordering requirement.+ // In non-first stage modes, we accumulate data (using `merge_batch`)+ // from different partitions (i.e. merge partial results). During+ // this merge, we consider the ordering of each partial result.+ // Hence, we do not need to use the ordering requirement in such+ // modes as long as partial results are generated with the+ // correct ordering.+ fn_reqs.filter(|_| is_order_sensitive(aggr_expr) && mode.is_first_stage())}).collect::<Vec<_>>();let mut aggregator_reverse_reqs = None;@@ -645,7 +647,6 @@ impl AggregateExec {}let mut aggregation_ordering = calc_aggregation_ordering(&input, &group_by);-let required_input_ordering = calc_required_input_ordering(&input,&mut aggr_expr,@@ -1216,14 +1217,26 @@ fn evaluate_group_by(mod tests {use super::*;use crate::execution::context::SessionConfig;+ use crate::physical_plan::aggregates::GroupByOrderMode::{+ FullyOrdered, PartiallyOrdered,+ };use crate::physical_plan::aggregates::{get_finest_requirement, get_working_mode, AggregateExec, AggregateMode,PhysicalGroupBy,};+ use crate::physical_plan::coalesce_batches::CoalesceBatchesExec;+ use crate::physical_plan::coalesce_partitions::CoalescePartitionsExec;use crate::physical_plan::expressions::{col, Avg};+ use crate::physical_plan::memory::MemoryExec;+ use crate::physical_plan::{+ DisplayAs, ExecutionPlan, Partitioning, RecordBatchStream,+ SendableRecordBatchStream, Statistics,+ };+ use crate::prelude::SessionContext;use crate::test::exec::{assert_strong_count_converges_to_zero, BlockingExec};use crate::test::{assert_is_pending, csv_exec_sorted};- use crate::{assert_batches_sorted_eq, physical_plan::common};+ use crate::{assert_batches_eq, assert_batches_sorted_eq, physical_plan::common};+use arrow::array::{Float64Array, UInt32Array};use arrow::compute::{concat_batches, SortOptions};use arrow::datatypes::{DataType, Field, Schema, SchemaRef};@@ -1231,27 +1244,18 @@ mod tests {use datafusion_common::{DataFusionError, Result, ScalarValue};use datafusion_execution::runtime_env::{RuntimeConfig, RuntimeEnv};use datafusion_physical_expr::expressions::{- lit, ApproxDistinct, Column, Count, FirstValue, Median,+ lit, ApproxDistinct, Column, Count, FirstValue, LastValue, Median,};use datafusion_physical_expr::{AggregateExpr, EquivalenceProperties, OrderingEquivalenceProperties,PhysicalExpr, PhysicalSortExpr,};- use futures::{FutureExt, Stream};+use std::any::Any;use std::sync::Arc;use std::task::{Context, Poll};- use super::StreamType;- use crate::physical_plan::aggregates::GroupByOrderMode::{- FullyOrdered, PartiallyOrdered,- };- use crate::physical_plan::coalesce_partitions::CoalescePartitionsExec;- use crate::physical_plan::{- DisplayAs, ExecutionPlan, Partitioning, RecordBatchStream,- SendableRecordBatchStream, Statistics,- };- use crate::prelude::SessionContext;+ use futures::{FutureExt, Stream};// Generate a schema which consists of 5 columns (a, b, c, d, e)fn create_test_schema() -> Result<SchemaRef> {@@ -1370,6 +1374,57 @@ mod tests {)}+ /// Generates some mock data for aggregate tests.+ fn some_data_v2() -> (Arc<Schema>, Vec<RecordBatch>) {+ // Define a schema:+ let schema = Arc::new(Schema::new(vec![+ Field::new("a", DataType::UInt32, false),+ Field::new("b", DataType::Float64, false),+ ]));++ // Generate data so that first and last value results are at 2nd and+ // 3rd partitions. With this construction, we guarantee we don't receive+ // the expected result by accident, but merging actually works properly;+ // i.e. it doesn't depend on the data insertion order.+ (+ schema.clone(),+ vec![+ RecordBatch::try_new(+ schema.clone(),+ vec![+ Arc::new(UInt32Array::from(vec![2, 3, 4, 4])),+ Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0])),+ ],+ )+ .unwrap(),+ RecordBatch::try_new(+ schema.clone(),+ vec![+ Arc::new(UInt32Array::from(vec![2, 3, 3, 4])),+ Arc::new(Float64Array::from(vec![0.0, 1.0, 2.0, 3.0])),+ ],+ )+ .unwrap(),+ RecordBatch::try_new(+ schema.clone(),+ vec![+ Arc::new(UInt32Array::from(vec![2, 3, 3, 4])),+ Arc::new(Float64Array::from(vec![3.0, 4.0, 5.0, 6.0])),+ ],+ )+ .unwrap(),+ RecordBatch::try_new(+ schema,+ vec![+ Arc::new(UInt32Array::from(vec![2, 3, 3, 4])),+ Arc::new(Float64Array::from(vec![2.0, 3.0, 4.0, 5.0])),+ ],+ )+ .unwrap(),+ ],+ )+ }+async fn check_grouping_sets(input: Arc<dyn ExecutionPlan>) -> Result<()> {let input_schema = input.schema();@@ -1885,6 +1940,134 @@ mod tests {Ok(())}+ #[tokio::test]+ async fn run_first_last_multi_partitions() -> Result<()> {+ for use_coalesce_batches in [false, true] {+ for is_first_acc in [false, true] {+ first_last_multi_partitions(use_coalesce_batches, is_first_acc).await?+ }+ }+ Ok(())+ }++ // This function either constructs the physical plan below,+ //+ // "AggregateExec: mode=Final, gby=[a@0 as a], aggr=[FIRST_VALUE(b)]",+ // " CoalesceBatchesExec: target_batch_size=1024",+ // " CoalescePartitionsExec",+ // " AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[FIRST_VALUE(b)], ordering_mode=None",+ // " MemoryExec: partitions=4, partition_sizes=[1, 1, 1, 1]",+ //+ // or+ //+ // "AggregateExec: mode=Final, gby=[a@0 as a], aggr=[FIRST_VALUE(b)]",+ // " CoalescePartitionsExec",+ // " AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[FIRST_VALUE(b)], ordering_mode=None",+ // " MemoryExec: partitions=4, partition_sizes=[1, 1, 1, 1]",+ //+ // and checks whether the function `merge_batch` works correctly for+ // FIRST_VALUE and LAST_VALUE functions.+ async fn first_last_multi_partitions(+ use_coalesce_batches: bool,+ is_first_acc: bool,+ ) -> Result<()> {+ let session_ctx = SessionContext::new();+ let task_ctx = session_ctx.task_ctx();++ let (schema, data) = some_data_v2();+ let partition1 = data[0].clone();+ let partition2 = data[1].clone();+ let partition3 = data[2].clone();+ let partition4 = data[3].clone();++ let groups =+ PhysicalGroupBy::new_single(vec![(col("a", &schema)?, "a".to_string())]);++ let ordering_req = vec![PhysicalSortExpr {+ expr: col("b", &schema)?,+ options: SortOptions::default(),+ }];+ let aggregates: Vec<Arc<dyn AggregateExpr>> = if is_first_acc {+ vec![Arc::new(FirstValue::new(+ col("b", &schema)?,+ "FIRST_VALUE(b)".to_string(),+ DataType::Float64,+ ordering_req.clone(),+ vec![DataType::Float64],+ ))]+ } else {+ vec![Arc::new(LastValue::new(+ col("b", &schema)?,+ "LAST_VALUE(b)".to_string(),+ DataType::Float64,+ ordering_req.clone(),+ vec![DataType::Float64],+ ))]+ };++ let memory_exec = Arc::new(MemoryExec::try_new(+ &[+ vec![partition1],+ vec![partition2],+ vec![partition3],+ vec![partition4],+ ],+ schema.clone(),+ None,+ )?);+ let aggregate_exec = Arc::new(AggregateExec::try_new(+ AggregateMode::Partial,+ groups.clone(),+ aggregates.clone(),+ vec![None],+ vec![Some(ordering_req.clone())],+ memory_exec,+ schema.clone(),+ )?);+ let coalesce = if use_coalesce_batches {+ let coalesce = Arc::new(CoalescePartitionsExec::new(aggregate_exec));+ Arc::new(CoalesceBatchesExec::new(coalesce, 1024)) as Arc<dyn ExecutionPlan>+ } else {+ Arc::new(CoalescePartitionsExec::new(aggregate_exec))+ as Arc<dyn ExecutionPlan>+ };+ let aggregate_final = Arc::new(AggregateExec::try_new(+ AggregateMode::Final,+ groups,+ aggregates.clone(),+ vec![None],+ vec![Some(ordering_req)],+ coalesce,+ schema,+ )?) as Arc<dyn ExecutionPlan>;++ let result = crate::physical_plan::collect(aggregate_final, task_ctx).await?;+ if is_first_acc {+ let expected = vec![+ "+---+----------------+",+ "| a | FIRST_VALUE(b) |",+ "+---+----------------+",+ "| 2 | 0.0 |",+ "| 3 | 1.0 |",+ "| 4 | 3.0 |",+ "+---+----------------+",+ ];+ assert_batches_eq!(expected, &result);+ } else {+ let expected = vec![+ "+---+---------------+",+ "| a | LAST_VALUE(b) |",+ "+---+---------------+",+ "| 2 | 3.0 |",+ "| 3 | 5.0 |",+ "| 4 | 6.0 |",+ "+---+---------------+",+ ];+ assert_batches_eq!(expected, &result);+ };+ Ok(())+ }+#[tokio::test]async fn test_get_finest_requirements() -> Result<()> {let test_schema = create_test_schema()?;diff --git a/datafusion/core/src/physical_plan/aggregates/order/mod.rs b/datafusion/core/src/physical_plan/aggregates/order/mod.rsindex ebe662c980..f0b49872b1 100644--- a/datafusion/core/src/physical_plan/aggregates/order/mod.rs+++ b/datafusion/core/src/physical_plan/aggregates/order/mod.rs@@ -52,7 +52,6 @@ impl GroupOrdering {} = ordering;Ok(match mode {- GroupByOrderMode::None => GroupOrdering::None,GroupByOrderMode::PartiallyOrdered => {let partial =GroupOrderingPartial::try_new(input_schema, order_indices, ordering)?;diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rsindex 176f3cbe50..72fd554ed7 100644--- a/datafusion/core/src/physical_planner.rs+++ b/datafusion/core/src/physical_planner.rs@@ -707,7 +707,7 @@ impl DefaultPhysicalPlanner {groups.clone(),aggregates.clone(),filters.clone(),- order_bys.clone(),+ order_bys,input_exec,physical_input_schema.clone(),)?);@@ -719,6 +719,14 @@ impl DefaultPhysicalPlanner {&& session_state.config().target_partitions() > 1&& session_state.config().repartition_aggregations();+ // Some aggregators may be modified during initialization for+ // optimization purposes. For example, a FIRST_VALUE may turn+ // into a LAST_VALUE with the reverse ordering requirement.+ // To reflect such changes to subsequent stages, use the updated+ // `AggregateExpr`/`PhysicalSortExpr` objects.+ let updated_aggregates = initial_aggr.aggr_expr.clone();+ let updated_order_bys = initial_aggr.order_by_expr.clone();+let (initial_aggr, next_partition_mode): (Arc<dyn ExecutionPlan>,AggregateMode,@@ -742,9 +750,9 @@ impl DefaultPhysicalPlanner {Ok(Arc::new(AggregateExec::try_new(next_partition_mode,final_grouping_set,- aggregates,+ updated_aggregates,filters,- order_bys,+ updated_order_bys,initial_aggr,physical_input_schema.clone(),)?))diff --git a/datafusion/core/tests/sqllogictests/test_files/groupby.slt b/datafusion/core/tests/sqllogictests/test_files/groupby.sltindex 5db2ad9280..898abceefb 100644--- a/datafusion/core/tests/sqllogictests/test_files/groupby.slt+++ b/datafusion/core/tests/sqllogictests/test_files/groupby.slt@@ -1960,21 +1960,20 @@ SortPreservingMergeExec: [col0@0 ASC NULLS LAST]--SortExec: expr=[col0@0 ASC NULLS LAST]----ProjectionExec: expr=[col0@0 as col0, LAST_VALUE(r.col1) ORDER BY [r.col0 ASC NULLS LAST]@3 as last_col1]------AggregateExec: mode=FinalPartitioned, gby=[col0@0 as col0, col1@1 as col1, col2@2 as col2], aggr=[LAST_VALUE(r.col1)]---------SortExec: expr=[col0@3 ASC NULLS LAST]-----------CoalesceBatchesExec: target_batch_size=8192-------------RepartitionExec: partitioning=Hash([col0@0, col1@1, col2@2], 4), input_partitions=4---------------AggregateExec: mode=Partial, gby=[col0@0 as col0, col1@1 as col1, col2@2 as col2], aggr=[LAST_VALUE(r.col1)], ordering_mode=PartiallyOrdered-----------------SortExec: expr=[col0@3 ASC NULLS LAST]-------------------CoalesceBatchesExec: target_batch_size=8192---------------------HashJoinExec: mode=Partitioned, join_type=Inner, on=[(col0@0, col0@0)]-----------------------CoalesceBatchesExec: target_batch_size=8192-------------------------RepartitionExec: partitioning=Hash([col0@0], 4), input_partitions=4---------------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1-----------------------------MemoryExec: partitions=1, partition_sizes=[3]-----------------------CoalesceBatchesExec: target_batch_size=8192-------------------------RepartitionExec: partitioning=Hash([col0@0], 4), input_partitions=4---------------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1-----------------------------MemoryExec: partitions=1, partition_sizes=[3]+--------CoalesceBatchesExec: target_batch_size=8192+----------RepartitionExec: partitioning=Hash([col0@0, col1@1, col2@2], 4), input_partitions=4+------------AggregateExec: mode=Partial, gby=[col0@0 as col0, col1@1 as col1, col2@2 as col2], aggr=[LAST_VALUE(r.col1)], ordering_mode=PartiallyOrdered+--------------SortExec: expr=[col0@3 ASC NULLS LAST]+----------------CoalesceBatchesExec: target_batch_size=8192+------------------HashJoinExec: mode=Partitioned, join_type=Inner, on=[(col0@0, col0@0)]+--------------------CoalesceBatchesExec: target_batch_size=8192+----------------------RepartitionExec: partitioning=Hash([col0@0], 4), input_partitions=4+------------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1+--------------------------MemoryExec: partitions=1, partition_sizes=[3]+--------------------CoalesceBatchesExec: target_batch_size=8192+----------------------RepartitionExec: partitioning=Hash([col0@0], 4), input_partitions=4+------------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1+--------------------------MemoryExec: partitions=1, partition_sizes=[3]# Columns in the table are a,b,c,d. Source is CsvExec which is ordered by# a,b,c column. Column a has cardinality 2, column b has cardinality 4.@@ -2213,6 +2212,21 @@ CREATE TABLE sales_global (zip_code INT,(1, 'TUR', 4, '2022-01-03 10:00:00'::timestamp, 'TRY', 100.0),(0, 'GRC', 4, '2022-01-03 10:00:00'::timestamp, 'EUR', 80.0)+# create a new table named exchange rates+statement ok+CREATE TABLE exchange_rates (+ sn INTEGER,+ ts TIMESTAMP,+ currency_from VARCHAR(3),+ currency_to VARCHAR(3),+ rate DECIMAL(10,2)+) as VALUES+ (0, '2022-01-01 06:00:00'::timestamp, 'EUR', 'USD', 1.10),+ (1, '2022-01-01 08:00:00'::timestamp, 'TRY', 'USD', 0.10),+ (2, '2022-01-01 11:30:00'::timestamp, 'EUR', 'USD', 1.12),+ (3, '2022-01-02 12:00:00'::timestamp, 'TRY', 'USD', 0.11),+ (4, '2022-01-03 10:00:00'::timestamp, 'EUR', 'USD', 1.12)+# test_ordering_sensitive_aggregation# ordering sensitive requirement should add a SortExec in the final plan. To satisfy amount ASC# in the aggregation@@ -2689,13 +2703,12 @@ SortPreservingMergeExec: [country@0 ASC NULLS LAST]--SortExec: expr=[country@0 ASC NULLS LAST]----ProjectionExec: expr=[country@0 as country, FIRST_VALUE(sales_global.amount) ORDER BY [sales_global.ts ASC NULLS LAST]@1 as fv1, LAST_VALUE(sales_global.amount) ORDER BY [sales_global.ts ASC NULLS LAST]@2 as fv2]------AggregateExec: mode=FinalPartitioned, gby=[country@0 as country], aggr=[FIRST_VALUE(sales_global.amount), LAST_VALUE(sales_global.amount)]---------SortExec: expr=[ts@1 ASC NULLS LAST]-----------CoalesceBatchesExec: target_batch_size=8192-------------RepartitionExec: partitioning=Hash([country@0], 8), input_partitions=8---------------AggregateExec: mode=Partial, gby=[country@0 as country], aggr=[FIRST_VALUE(sales_global.amount), LAST_VALUE(sales_global.amount)], ordering_mode=None-----------------SortExec: expr=[ts@1 ASC NULLS LAST]-------------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1---------------------MemoryExec: partitions=1, partition_sizes=[1]+--------CoalesceBatchesExec: target_batch_size=8192+----------RepartitionExec: partitioning=Hash([country@0], 8), input_partitions=8+------------AggregateExec: mode=Partial, gby=[country@0 as country], aggr=[FIRST_VALUE(sales_global.amount), LAST_VALUE(sales_global.amount)]+--------------SortExec: expr=[ts@1 ASC NULLS LAST]+----------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1+------------------MemoryExec: partitions=1, partition_sizes=[1]query TRRSELECT country, FIRST_VALUE(amount ORDER BY ts ASC) AS fv1,@@ -2727,13 +2740,12 @@ SortPreservingMergeExec: [country@0 ASC NULLS LAST]--SortExec: expr=[country@0 ASC NULLS LAST]----ProjectionExec: expr=[country@0 as country, FIRST_VALUE(sales_global.amount) ORDER BY [sales_global.ts ASC NULLS LAST]@1 as fv1, LAST_VALUE(sales_global.amount) ORDER BY [sales_global.ts DESC NULLS FIRST]@2 as fv2]------AggregateExec: mode=FinalPartitioned, gby=[country@0 as country], aggr=[FIRST_VALUE(sales_global.amount), FIRST_VALUE(sales_global.amount)]---------SortExec: expr=[ts@1 ASC NULLS LAST]-----------CoalesceBatchesExec: target_batch_size=8192-------------RepartitionExec: partitioning=Hash([country@0], 8), input_partitions=8---------------AggregateExec: mode=Partial, gby=[country@0 as country], aggr=[FIRST_VALUE(sales_global.amount), FIRST_VALUE(sales_global.amount)], ordering_mode=None-----------------SortExec: expr=[ts@1 ASC NULLS LAST]-------------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1---------------------MemoryExec: partitions=1, partition_sizes=[1]+--------CoalesceBatchesExec: target_batch_size=8192+----------RepartitionExec: partitioning=Hash([country@0], 8), input_partitions=8+------------AggregateExec: mode=Partial, gby=[country@0 as country], aggr=[FIRST_VALUE(sales_global.amount), FIRST_VALUE(sales_global.amount)]+--------------SortExec: expr=[ts@1 ASC NULLS LAST]+----------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1+------------------MemoryExec: partitions=1, partition_sizes=[1]query TRRSELECT country, FIRST_VALUE(amount ORDER BY ts ASC) AS fv1,@@ -2760,8 +2772,8 @@ Projection: FIRST_VALUE(sales_global.amount) ORDER BY [sales_global.ts ASC NULLSphysical_planProjectionExec: expr=[FIRST_VALUE(sales_global.amount) ORDER BY [sales_global.ts ASC NULLS LAST]@0 as fv1, LAST_VALUE(sales_global.amount) ORDER BY [sales_global.ts ASC NULLS LAST]@1 as fv2]--AggregateExec: mode=Final, gby=[], aggr=[FIRST_VALUE(sales_global.amount), LAST_VALUE(sales_global.amount)]-----SortPreservingMergeExec: [ts@0 ASC NULLS LAST]-------AggregateExec: mode=Partial, gby=[], aggr=[FIRST_VALUE(sales_global.amount), LAST_VALUE(sales_global.amount)], ordering_mode=None+----CoalescePartitionsExec+------AggregateExec: mode=Partial, gby=[], aggr=[FIRST_VALUE(sales_global.amount), LAST_VALUE(sales_global.amount)]--------SortExec: expr=[ts@0 ASC NULLS LAST]----------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1------------MemoryExec: partitions=1, partition_sizes=[1]@@ -2787,8 +2799,8 @@ Projection: FIRST_VALUE(sales_global.amount) ORDER BY [sales_global.ts ASC NULLSphysical_planProjectionExec: expr=[FIRST_VALUE(sales_global.amount) ORDER BY [sales_global.ts ASC NULLS LAST]@0 as fv1, LAST_VALUE(sales_global.amount) ORDER BY [sales_global.ts DESC NULLS FIRST]@1 as fv2]--AggregateExec: mode=Final, gby=[], aggr=[FIRST_VALUE(sales_global.amount), FIRST_VALUE(sales_global.amount)]-----SortPreservingMergeExec: [ts@0 ASC NULLS LAST]-------AggregateExec: mode=Partial, gby=[], aggr=[FIRST_VALUE(sales_global.amount), FIRST_VALUE(sales_global.amount)], ordering_mode=None+----CoalescePartitionsExec+------AggregateExec: mode=Partial, gby=[], aggr=[FIRST_VALUE(sales_global.amount), FIRST_VALUE(sales_global.amount)]--------SortExec: expr=[ts@0 ASC NULLS LAST]----------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1------------MemoryExec: partitions=1, partition_sizes=[1]@@ -2812,8 +2824,8 @@ Projection: ARRAY_AGG(sales_global.amount) ORDER BY [sales_global.ts ASC NULLS Lphysical_planProjectionExec: expr=[ARRAY_AGG(sales_global.amount) ORDER BY [sales_global.ts ASC NULLS LAST]@0 as array_agg1]--AggregateExec: mode=Final, gby=[], aggr=[ARRAY_AGG(sales_global.amount)]-----SortPreservingMergeExec: [ts@0 ASC NULLS LAST]-------AggregateExec: mode=Partial, gby=[], aggr=[ARRAY_AGG(sales_global.amount)], ordering_mode=None+----CoalescePartitionsExec+------AggregateExec: mode=Partial, gby=[], aggr=[ARRAY_AGG(sales_global.amount)]--------SortExec: expr=[ts@0 ASC NULLS LAST]----------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1------------MemoryExec: partitions=1, partition_sizes=[1]@@ -2836,8 +2848,8 @@ Projection: ARRAY_AGG(sales_global.amount) ORDER BY [sales_global.ts DESC NULLSphysical_planProjectionExec: expr=[ARRAY_AGG(sales_global.amount) ORDER BY [sales_global.ts DESC NULLS FIRST]@0 as array_agg1]--AggregateExec: mode=Final, gby=[], aggr=[ARRAY_AGG(sales_global.amount)]-----SortPreservingMergeExec: [ts@0 DESC]-------AggregateExec: mode=Partial, gby=[], aggr=[ARRAY_AGG(sales_global.amount)], ordering_mode=None+----CoalescePartitionsExec+------AggregateExec: mode=Partial, gby=[], aggr=[ARRAY_AGG(sales_global.amount)]--------SortExec: expr=[ts@0 DESC]----------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1------------MemoryExec: partitions=1, partition_sizes=[1]@@ -2860,8 +2872,8 @@ Projection: ARRAY_AGG(sales_global.amount) ORDER BY [sales_global.amount ASC NULphysical_planProjectionExec: expr=[ARRAY_AGG(sales_global.amount) ORDER BY [sales_global.amount ASC NULLS LAST]@0 as array_agg1]--AggregateExec: mode=Final, gby=[], aggr=[ARRAY_AGG(sales_global.amount)]-----SortPreservingMergeExec: [amount@0 ASC NULLS LAST]-------AggregateExec: mode=Partial, gby=[], aggr=[ARRAY_AGG(sales_global.amount)], ordering_mode=None+----CoalescePartitionsExec+------AggregateExec: mode=Partial, gby=[], aggr=[ARRAY_AGG(sales_global.amount)]--------SortExec: expr=[amount@0 ASC NULLS LAST]----------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1------------MemoryExec: partitions=1, partition_sizes=[1]@@ -2889,13 +2901,12 @@ SortPreservingMergeExec: [country@0 ASC NULLS LAST]--SortExec: expr=[country@0 ASC NULLS LAST]----ProjectionExec: expr=[country@0 as country, ARRAY_AGG(sales_global.amount) ORDER BY [sales_global.amount ASC NULLS LAST]@1 as array_agg1]------AggregateExec: mode=FinalPartitioned, gby=[country@0 as country], aggr=[ARRAY_AGG(sales_global.amount)]---------SortExec: expr=[amount@1 ASC NULLS LAST]-----------CoalesceBatchesExec: target_batch_size=8192-------------RepartitionExec: partitioning=Hash([country@0], 8), input_partitions=8---------------AggregateExec: mode=Partial, gby=[country@0 as country], aggr=[ARRAY_AGG(sales_global.amount)], ordering_mode=None-----------------SortExec: expr=[amount@1 ASC NULLS LAST]-------------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1---------------------MemoryExec: partitions=1, partition_sizes=[1]+--------CoalesceBatchesExec: target_batch_size=8192+----------RepartitionExec: partitioning=Hash([country@0], 8), input_partitions=8+------------AggregateExec: mode=Partial, gby=[country@0 as country], aggr=[ARRAY_AGG(sales_global.amount)]+--------------SortExec: expr=[amount@1 ASC NULLS LAST]+----------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1+------------------MemoryExec: partitions=1, partition_sizes=[1]query T?SELECT country, ARRAY_AGG(amount ORDER BY amount ASC) AS array_agg1@@ -2926,13 +2937,12 @@ SortPreservingMergeExec: [country@0 ASC NULLS LAST]--SortExec: expr=[country@0 ASC NULLS LAST]----ProjectionExec: expr=[country@0 as country, ARRAY_AGG(sales_global.amount) ORDER BY [sales_global.amount DESC NULLS FIRST]@1 as amounts, FIRST_VALUE(sales_global.amount) ORDER BY [sales_global.amount ASC NULLS LAST]@2 as fv1, LAST_VALUE(sales_global.amount) ORDER BY [sales_global.amount DESC NULLS FIRST]@3 as fv2]------AggregateExec: mode=FinalPartitioned, gby=[country@0 as country], aggr=[ARRAY_AGG(sales_global.amount), LAST_VALUE(sales_global.amount), LAST_VALUE(sales_global.amount)]---------SortExec: expr=[amount@1 DESC]-----------CoalesceBatchesExec: target_batch_size=8192-------------RepartitionExec: partitioning=Hash([country@0], 8), input_partitions=8---------------AggregateExec: mode=Partial, gby=[country@0 as country], aggr=[ARRAY_AGG(sales_global.amount), LAST_VALUE(sales_global.amount), LAST_VALUE(sales_global.amount)], ordering_mode=None-----------------SortExec: expr=[amount@1 DESC]-------------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1---------------------MemoryExec: partitions=1, partition_sizes=[1]+--------CoalesceBatchesExec: target_batch_size=8192+----------RepartitionExec: partitioning=Hash([country@0], 8), input_partitions=8+------------AggregateExec: mode=Partial, gby=[country@0 as country], aggr=[ARRAY_AGG(sales_global.amount), LAST_VALUE(sales_global.amount), LAST_VALUE(sales_global.amount)]+--------------SortExec: expr=[amount@1 DESC]+----------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1+------------------MemoryExec: partitions=1, partition_sizes=[1]query T?RRSELECT country, ARRAY_AGG(amount ORDER BY amount DESC) AS amounts,@@ -2946,6 +2956,39 @@ FRA [200.0, 50.0] 50 50GRC [80.0, 30.0] 30 30TUR [100.0, 75.0] 75 75+# make sure that query below runs in multi partitions+statement ok+set datafusion.execution.target_partitions = 8;++query ?+SELECT ARRAY_AGG(e.rate ORDER BY e.sn)+FROM sales_global AS s+JOIN exchange_rates AS e+ON s.currency = e.currency_from AND+ e.currency_to = 'USD' AND+ s.ts >= e.ts+GROUP BY s.sn+ORDER BY s.sn;+----+[1.10]+[1.10]+[0.10]+[1.10, 1.12]+[1.10, 0.10, 1.12, 0.11, 1.12]+++query I+SELECT FIRST_VALUE(C order by c ASC) as first_c+FROM multiple_ordered_table+GROUP BY d+ORDER BY first_c+----+0+1+4+9+15+query ITIPTRSELECT s.zip_code, s.country, s.sn, s.ts, s.currency, LAST_VALUE(e.amount ORDER BY e.sn) AS last_rateFROM sales_global AS sdiff --git a/datafusion/physical-expr/src/aggregate/array_agg_ordered.rs b/datafusion/physical-expr/src/aggregate/array_agg_ordered.rsindex f0eb442af0..d91f06fc76 100644--- a/datafusion/physical-expr/src/aggregate/array_agg_ordered.rs+++ b/datafusion/physical-expr/src/aggregate/array_agg_ordered.rs@@ -18,9 +18,16 @@//! Defines physical expressions which specify ordering requirement//! that can evaluated at runtime during query execution+use std::any::Any;+use std::cmp::Ordering;+use std::collections::BinaryHeap;+use std::fmt::Debug;+use std::sync::Arc;+use crate::aggregate::utils::{down_cast_any_ref, ordering_fields};use crate::expressions::format_state_name;use crate::{AggregateExpr, LexOrdering, PhysicalExpr, PhysicalSortExpr};+use arrow::array::ArrayRef;use arrow::datatypes::{DataType, Field};use arrow_array::{Array, ListArray};@@ -28,12 +35,8 @@ use arrow_schema::{Fields, SortOptions};use datafusion_common::utils::{compare_rows, get_row_at_idx};use datafusion_common::{DataFusionError, Result, ScalarValue};use datafusion_expr::Accumulator;+use itertools::izip;-use std::any::Any;-use std::cmp::Ordering;-use std::collections::BinaryHeap;-use std::fmt::Debug;-use std::sync::Arc;/// Expression for a ARRAY_AGG(ORDER BY) aggregation./// When aggregation works in multiple partitions@@ -100,14 +103,9 @@ impl AggregateExpr for OrderSensitiveArrayAgg {let orderings = ordering_fields(&self.ordering_req, &self.order_by_data_types);fields.push(Field::new_list(format_state_name(&self.name, "array_agg_orderings"),- Field::new(- "item",- DataType::Struct(Fields::from(orderings.clone())),- true,- ),+ Field::new("item", DataType::Struct(Fields::from(orderings)), true),false,));- fields.extend(orderings);Ok(fields)}@@ -207,6 +205,10 @@ impl Accumulator for OrderSensitiveArrayAggAccumulator {let mut partition_values = vec![];// Stores ordering requirement expression results coming from each partitionlet mut partition_ordering_values = vec![];++ // Existing values should be merged also.+ partition_values.push(self.values.clone());+ partition_ordering_values.push(self.ordering_values.clone());for index in 0..agg_orderings.len() {let ordering = ScalarValue::try_from_array(agg_orderings, index)?;// Ordering requirement expression values for each entry in the ARRAY_AGG list@@ -228,11 +230,13 @@ impl Accumulator for OrderSensitiveArrayAggAccumulator {.iter().map(|sort_expr| sort_expr.options).collect::<Vec<_>>();- self.values = merge_ordered_arrays(+ let (new_values, new_orderings) = merge_ordered_arrays(&partition_values,&partition_ordering_values,&sort_options,)?;+ self.values = new_values;+ self.ordering_values = new_orderings;} else {return Err(DataFusionError::Execution("Expects to receive a list array".to_string(),@@ -244,17 +248,6 @@ impl Accumulator for OrderSensitiveArrayAggAccumulator {fn state(&self) -> Result<Vec<ScalarValue>> {let mut result = vec![self.evaluate()?];result.push(self.evaluate_orderings()?);- let last_ordering = if let Some(ordering) = self.ordering_values.last() {- ordering.clone()- } else {- // In case ordering is empty, construct ordering as NULL:- self.datatypes- .iter()- .skip(1)- .map(ScalarValue::try_from)- .collect::<Result<Vec<_>>>()?- };- result.extend(last_ordering);Ok(result)}@@ -426,7 +419,7 @@ fn merge_ordered_arrays(ordering_values: &[Vec<Vec<ScalarValue>>],// Defines according to which ordering comparisons should be done.sort_options: &[SortOptions],-) -> Result<Vec<ScalarValue>> {+) -> Result<(Vec<ScalarValue>, Vec<Vec<ScalarValue>>)> {// Keep track the most recent data of each branch, in binary heap data structure.let mut heap: BinaryHeap<CustomElement> = BinaryHeap::new();@@ -449,6 +442,7 @@ fn merge_ordered_arrays(.map(|idx| values[idx].len()).collect::<Vec<_>>();let mut merged_values = vec![];+ let mut merged_orderings = vec![];// Continue iterating the loop until consuming data of all branches.loop {let min_elem = if let Some(min_elem) = heap.pop() {@@ -490,6 +484,7 @@ fn merge_ordered_arrays(indices[branch_idx] += 1;let row_idx = indices[branch_idx];merged_values.push(min_elem.value.clone());+ merged_orderings.push(min_elem.ordering.clone());if row_idx < end_indices[branch_idx] {// Push next entry in the most recently consumed branch to the heap// If there is an available entry@@ -500,7 +495,7 @@ fn merge_ordered_arrays(}}- Ok(merged_values)+ Ok((merged_values, merged_orderings))}#[cfg(test)]@@ -553,14 +548,28 @@ mod tests {.collect::<Result<Vec<_>>>()?;let expected =Arc::new(Int64Array::from(vec![0, 0, 1, 1, 2, 2, 3, 3, 4, 4])) as ArrayRef;+ let expected_ts = vec![+ Arc::new(Int64Array::from(vec![0, 0, 0, 0, 1, 1, 1, 1, 2, 2])) as ArrayRef,+ Arc::new(Int64Array::from(vec![0, 0, 1, 1, 2, 2, 3, 3, 4, 4])) as ArrayRef,+ ];- let merged_vals = merge_ordered_arrays(+ let (merged_vals, merged_ts) = merge_ordered_arrays(&[lhs_vals, rhs_vals],&[lhs_orderings, rhs_orderings],&sort_options,)?;let merged_vals = ScalarValue::iter_to_array(merged_vals.into_iter())?;+ let merged_ts = (0..merged_ts[0].len())+ .map(|col_idx| {+ ScalarValue::iter_to_array(+ (0..merged_ts.len())+ .map(|row_idx| merged_ts[row_idx][col_idx].clone()),+ )+ })+ .collect::<Result<Vec<_>>>()?;+assert_eq!(&merged_vals, &expected);+ assert_eq!(&merged_ts, &expected_ts);Ok(())}@@ -607,15 +616,27 @@ mod tests {.collect::<Result<Vec<_>>>()?;let expected =Arc::new(Int64Array::from(vec![0, 0, 1, 1, 2, 2, 1, 1, 2, 2])) as ArrayRef;-- let merged_vals = merge_ordered_arrays(+ let expected_ts = vec![+ Arc::new(Int64Array::from(vec![2, 2, 1, 1, 1, 1, 0, 0, 0, 0])) as ArrayRef,+ Arc::new(Int64Array::from(vec![4, 4, 3, 3, 2, 2, 1, 1, 0, 0])) as ArrayRef,+ ];+ let (merged_vals, merged_ts) = merge_ordered_arrays(&[lhs_vals, rhs_vals],&[lhs_orderings, rhs_orderings],&sort_options,)?;let merged_vals = ScalarValue::iter_to_array(merged_vals.into_iter())?;+ let merged_ts = (0..merged_ts[0].len())+ .map(|col_idx| {+ ScalarValue::iter_to_array(+ (0..merged_ts.len())+ .map(|row_idx| merged_ts[row_idx][col_idx].clone()),+ )+ })+ .collect::<Result<Vec<_>>>()?;assert_eq!(&merged_vals, &expected);+ assert_eq!(&merged_ts, &expected_ts);Ok(())}}diff --git a/datafusion/physical-expr/src/aggregate/first_last.rs b/datafusion/physical-expr/src/aggregate/first_last.rsindex 656f30a135..7e8930ce2a 100644--- a/datafusion/physical-expr/src/aggregate/first_last.rs+++ b/datafusion/physical-expr/src/aggregate/first_last.rs@@ -17,21 +17,23 @@//! Defines the FIRST_VALUE/LAST_VALUE aggregations.+use std::any::Any;+use std::sync::Arc;+use crate::aggregate::utils::{down_cast_any_ref, ordering_fields};use crate::expressions::format_state_name;use crate::{AggregateExpr, LexOrdering, PhysicalExpr, PhysicalSortExpr};use arrow::array::ArrayRef;-use arrow::datatypes::{DataType, Field};-use arrow_array::Array;-use datafusion_common::{Result, ScalarValue};-use datafusion_expr::Accumulator;-use arrow::compute;+use arrow::compute::{lexsort_to_indices, SortColumn};+use arrow::datatypes::{DataType, Field};use arrow_array::cast::AsArray;-use datafusion_common::utils::get_row_at_idx;-use std::any::Any;-use std::sync::Arc;+use arrow_array::{Array, BooleanArray};+use arrow_schema::SortOptions;+use datafusion_common::utils::{compare_rows, get_arrayref_at_indices, get_row_at_idx};+use datafusion_common::{DataFusionError, Result, ScalarValue};+use datafusion_expr::Accumulator;/// FIRST_VALUE aggregate expression#[derive(Debug)]@@ -76,6 +78,7 @@ impl AggregateExpr for FirstValue {Ok(Box::new(FirstValueAccumulator::try_new(&self.input_data_type,&self.order_by_data_types,+ self.ordering_req.clone(),)?))}@@ -132,6 +135,7 @@ impl AggregateExpr for FirstValue {Ok(Box::new(FirstValueAccumulator::try_new(&self.input_data_type,&self.order_by_data_types,+ self.ordering_req.clone(),)?))}}@@ -159,11 +163,17 @@ struct FirstValueAccumulator {// Stores ordering values, of the aggregator requirement corresponding to first value// of the aggregator. These values are used during merging of multiple partitions.orderings: Vec<ScalarValue>,+ // Stores the applicable ordering requirement.+ ordering_req: LexOrdering,}impl FirstValueAccumulator {/// Creates a new `FirstValueAccumulator` for the given `data_type`.- pub fn try_new(data_type: &DataType, ordering_dtypes: &[DataType]) -> Result<Self> {+ pub fn try_new(+ data_type: &DataType,+ ordering_dtypes: &[DataType],+ ordering_req: LexOrdering,+ ) -> Result<Self> {let orderings = ordering_dtypes.iter().map(ScalarValue::try_from)@@ -172,8 +182,16 @@ impl FirstValueAccumulator {first: value,is_set: false,orderings,+ ordering_req,})}++ // Updates state with the values in the given row.+ fn update_with_new_row(&mut self, row: &[ScalarValue]) {+ self.first = row[0].clone();+ self.orderings = row[1..].to_vec();+ self.is_set = true;+ }}impl Accumulator for FirstValueAccumulator {@@ -188,24 +206,41 @@ impl Accumulator for FirstValueAccumulator {// If we have seen first value, we shouldn't update itif !values[0].is_empty() && !self.is_set {let row = get_row_at_idx(values, 0)?;- // Update with last value in the array.- self.first = row[0].clone();- self.orderings = row[1..].to_vec();- self.is_set = true;+ // Update with first value in the array.+ self.update_with_new_row(&row);}Ok(())}fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {// FIRST_VALUE(first1, first2, first3, ...)- let last_idx = states.len() - 1;- let is_set_flags = &states[last_idx];- let flags = is_set_flags.as_boolean();- let mut filtered_first_vals = vec![];- for state in states.iter().take(last_idx) {- filtered_first_vals.push(compute::filter(state, flags)?)+ // last index contains is_set flag.+ let is_set_idx = states.len() - 1;+ let flags = states[is_set_idx].as_boolean();+ let filtered_states = filter_states_according_to_is_set(states, flags)?;+ // 1..is_set_idx range corresponds to ordering section+ let sort_cols =+ convert_to_sort_cols(&filtered_states[1..is_set_idx], &self.ordering_req);++ let ordered_states = if sort_cols.is_empty() {+ // When no ordering is given, use the existing state as is:+ filtered_states+ } else {+ let indices = lexsort_to_indices(&sort_cols, None)?;+ get_arrayref_at_indices(&filtered_states, &indices)?+ };+ if !ordered_states[0].is_empty() {+ let first_row = get_row_at_idx(&ordered_states, 0)?;+ let first_ordering = &first_row[1..];+ let sort_options = get_sort_options(&self.ordering_req);+ // Either there is no existing value, or there is an earlier version in new data.+ if !self.is_set+ || compare_rows(first_ordering, &self.orderings, &sort_options)?.is_lt()+ {+ self.update_with_new_row(&first_row);+ }}- self.update_batch(&filtered_first_vals)+ Ok(())}fn evaluate(&self) -> Result<ScalarValue> {@@ -263,6 +298,7 @@ impl AggregateExpr for LastValue {Ok(Box::new(LastValueAccumulator::try_new(&self.input_data_type,&self.order_by_data_types,+ self.ordering_req.clone(),)?))}@@ -319,6 +355,7 @@ impl AggregateExpr for LastValue {Ok(Box::new(LastValueAccumulator::try_new(&self.input_data_type,&self.order_by_data_types,+ self.ordering_req.clone(),)?))}}@@ -345,11 +382,17 @@ struct LastValueAccumulator {// occur due to empty partitions.is_set: bool,orderings: Vec<ScalarValue>,+ // Stores the applicable ordering requirement.+ ordering_req: LexOrdering,}impl LastValueAccumulator {/// Creates a new `LastValueAccumulator` for the given `data_type`.- pub fn try_new(data_type: &DataType, ordering_dtypes: &[DataType]) -> Result<Self> {+ pub fn try_new(+ data_type: &DataType,+ ordering_dtypes: &[DataType],+ ordering_req: LexOrdering,+ ) -> Result<Self> {let orderings = ordering_dtypes.iter().map(ScalarValue::try_from)@@ -358,8 +401,16 @@ impl LastValueAccumulator {last: ScalarValue::try_from(data_type)?,is_set: false,orderings,+ ordering_req,})}++ // Updates state with the values in the given row.+ fn update_with_new_row(&mut self, row: &[ScalarValue]) {+ self.last = row[0].clone();+ self.orderings = row[1..].to_vec();+ self.is_set = true;+ }}impl Accumulator for LastValueAccumulator {@@ -374,23 +425,43 @@ impl Accumulator for LastValueAccumulator {if !values[0].is_empty() {let row = get_row_at_idx(values, values[0].len() - 1)?;// Update with last value in the array.- self.last = row[0].clone();- self.orderings = row[1..].to_vec();- self.is_set = true;+ self.update_with_new_row(&row);}Ok(())}fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {// LAST_VALUE(last1, last2, last3, ...)- let last_idx = states.len() - 1;- let is_set_flags = &states[last_idx];- let flags = is_set_flags.as_boolean();- let mut filtered_first_vals = vec![];- for state in states.iter().take(last_idx) {- filtered_first_vals.push(compute::filter(state, flags)?)+ // last index contains is_set flag.+ let is_set_idx = states.len() - 1;+ let flags = states[is_set_idx].as_boolean();+ let filtered_states = filter_states_according_to_is_set(states, flags)?;+ // 1..is_set_idx range corresponds to ordering section+ let sort_cols =+ convert_to_sort_cols(&filtered_states[1..is_set_idx], &self.ordering_req);++ let ordered_states = if sort_cols.is_empty() {+ // When no ordering is given, use existing state as is:+ filtered_states+ } else {+ let indices = lexsort_to_indices(&sort_cols, None)?;+ get_arrayref_at_indices(&filtered_states, &indices)?+ };++ if !ordered_states[0].is_empty() {+ let last_idx = ordered_states[0].len() - 1;+ let last_row = get_row_at_idx(&ordered_states, last_idx)?;+ let last_ordering = &last_row[1..];+ let sort_options = get_sort_options(&self.ordering_req);+ // Either there is no existing value, or there is a newer (latest)+ // version in the new data:+ if !self.is_set+ || compare_rows(last_ordering, &self.orderings, &sort_options)?.is_gt()+ {+ self.update_with_new_row(&last_row);+ }}- self.update_batch(&filtered_first_vals)+ Ok(())}fn evaluate(&self) -> Result<ScalarValue> {@@ -405,20 +476,57 @@ impl Accumulator for LastValueAccumulator {}}+/// Filters states according to the `is_set` flag at the last column and returns+/// the resulting states.+fn filter_states_according_to_is_set(+ states: &[ArrayRef],+ flags: &BooleanArray,+) -> Result<Vec<ArrayRef>> {+ states+ .iter()+ .map(|state| compute::filter(state, flags).map_err(DataFusionError::ArrowError))+ .collect::<Result<Vec<_>>>()+}++/// Combines array refs and their corresponding orderings to construct `SortColumn`s.+fn convert_to_sort_cols(+ arrs: &[ArrayRef],+ sort_exprs: &[PhysicalSortExpr],+) -> Vec<SortColumn> {+ arrs.iter()+ .zip(sort_exprs.iter())+ .map(|(item, sort_expr)| SortColumn {+ values: item.clone(),+ options: Some(sort_expr.options),+ })+ .collect::<Vec<_>>()+}++/// Selects the sort option attribute from all the given `PhysicalSortExpr`s.+fn get_sort_options(ordering_req: &[PhysicalSortExpr]) -> Vec<SortOptions> {+ ordering_req+ .iter()+ .map(|item| item.options)+ .collect::<Vec<_>>()+}+#[cfg(test)]mod tests {use crate::aggregate::first_last::{FirstValueAccumulator, LastValueAccumulator};+use arrow_array::{ArrayRef, Int64Array};use arrow_schema::DataType;use datafusion_common::{Result, ScalarValue};use datafusion_expr::Accumulator;+use std::sync::Arc;#[test]fn test_first_last_value_value() -> Result<()> {let mut first_accumulator =- FirstValueAccumulator::try_new(&DataType::Int64, &[])?;- let mut last_accumulator = LastValueAccumulator::try_new(&DataType::Int64, &[])?;+ FirstValueAccumulator::try_new(&DataType::Int64, &[], vec![])?;+ let mut last_accumulator =+ LastValueAccumulator::try_new(&DataType::Int64, &[], vec![])?;// first value in the tuple is start of the range (inclusive),// second value in the tuple is end of the range (exclusive)let ranges: Vec<(i64, i64)> = vec![(0, 10), (1, 11), (2, 13)];