jayzhan211 commented on code in PR #27827:
URL: https://github.com/apache/datafusion/pull/27827#discussion_r4786481636


##########
datafusion/physical-plan/src/aggregates/mod.rs:
##########
@@ -2261,10 +2269,16 @@ impl ExecutionPlan for AggregateExec {
                 ..Self::clone(&*self)
             })),
             ChildrenPropertiesMode::Recompute => {
+                let aggr_expr = match self.mode.input_mode() {
+                    AggregateInputMode::Partial => {
+                        match_state_direction(self.aggr_expr(), &children[0])

Review Comment:
   @alamb I agree, and I tried it. The root cause is that a reversed 
`nth_value` stores its partial state in the reversed direction, so only a 
reversed `Final` can read it. `array_agg` had the same bug and fixed it inside 
the accumulator (#22597): a reversed accumulator emits its state in the 
original direction. Doing the same for `nth_value` passes all three of this 
PR's tests with the `AggregateExec` changes reverted, plus the full 
sqllogictest suite, and it no longer matters what sits between the two 
aggregates.
   
   @CuteChuanChuan could you switch to the change below, revert the 
`aggregates/mod.rs` code changes and keep your tests? It gives up one thing: a 
third-party UDAF that reverses into itself has to do the same, so the diff also 
documents that on `reverse_expr`.
   
   <details>
   <summary>Diff: nth_value emits reversed state in the original direction 
(tested: clippy, rustdoc, functions-aggregate tests, full 
sqllogictest)</summary>
   
   ```diff
   --- a/datafusion/expr/src/udaf.rs
   +++ b/datafusion/expr/src/udaf.rs
   @@ -817,6 +817,11 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + 
Send + Sync + Any {
        }
    
        /// Returns the reverse expression of the aggregate function.
   +    ///
   +    /// A reversed accumulator must emit [`Accumulator::state`] in the 
original
   +    /// direction: the aggregate that merges it may not be reversed.
   +    ///
   +    /// [`Accumulator::state`]: crate::Accumulator::state
        fn reverse_expr(&self) -> ReversedUDAF {
            ReversedUDAF::NotSupported
        }
   --- a/datafusion/functions-aggregate/src/nth_value.rs
   +++ b/datafusion/functions-aggregate/src/nth_value.rs
   @@ -153,7 +153,7 @@ impl AggregateUDFImpl for NthValueAgg {
    
            let data_type = acc_args.expr_fields[0].data_type();
            NthValueAccumulator::try_new(n, data_type, &ordering_dtypes, 
ordering)
   -            .map(|acc| Box::new(acc) as _)
   +            .map(|acc| Box::new(acc.with_reversed(acc_args.is_reversed)) as 
_)
        }
    
   @@ -324,6 +324,7 @@ pub struct NthValueAccumulator {
        datatypes: Vec<DataType>,
        /// Stores the ordering requirement of the `Accumulator`.
        ordering_req: LexOrdering,
   +    reversed: bool,
    }
    
   @@ -348,9 +349,20 @@ impl NthValueAccumulator {
                ordering_values: VecDeque::new(),
                datatypes,
                ordering_req,
   +            reversed: false,
            })
        }
    
   +    fn with_reversed(mut self, reversed: bool) -> Self {
   +        self.reversed = reversed;
   +        self
   +    }
   +
   +    fn reverse_lists(&mut self) {
   +        self.values.make_contiguous().reverse();
   +        self.ordering_values.make_contiguous().reverse();
   +    }
   +
   @@ -451,7 +463,10 @@ impl Accumulator for NthValueAccumulator {
            let mut partition_values = vec![self.values.clone()];
            // First entry in the state is the aggregation result.
            let array_agg_res = 
ScalarValue::convert_array_to_scalar_vec(&states[0])?;
   -        for v in array_agg_res.into_iter().flatten() {
   +        for mut v in array_agg_res.into_iter().flatten() {
   +            if self.reversed {
   +                v.reverse();
   +            }
                partition_values.push(v.into());
            }
   @@ -459,7 +474,7 @@ impl Accumulator for NthValueAccumulator {
            for partition_ordering_rows in orderings.into_iter().flatten() {
   -            let ordering_values = 
partition_ordering_rows.into_iter().map(|ordering_row| {
   +            let mut ordering_values = 
partition_ordering_rows.into_iter().map(|ordering_row| {
   @@ -472,6 +487,9 @@ impl Accumulator for NthValueAccumulator {
                }).collect::<Result<VecDeque<_>>>()?;
   +            if self.reversed {
   +                ordering_values.make_contiguous().reverse();
   +            }
                partition_ordering_values.push(ordering_values);
            }
   @@ -491,7 +509,17 @@ impl Accumulator for NthValueAccumulator {
        fn state(&mut self) -> Result<Vec<ScalarValue>> {
   -        Ok(vec![self.evaluate_values(), self.evaluate_orderings()?])
   +        if !self.reversed {
   +            return Ok(vec![self.evaluate_values(), 
self.evaluate_orderings()?]);
   +        }
   +        // A reversed accumulator emits its state in the original direction,
   +        // so the aggregate that merges it can be reversed or not (#27458).
   +        self.reverse_lists();
   +        let state = self
   +            .evaluate_orderings()
   +            .map(|orderings| vec![self.evaluate_values(), orderings]);
   +        self.reverse_lists();
   +        state
        }
   ```
   
   Unchanged context lines are trimmed. Each reversal is covered by your tests: 
removing the one in `state()` fails both `nth_value` queries and the unit test, 
and removing the two in `merge_batch` fails Query 2, where the `Final` is 
reversed at planning time.
   
   </details>
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to