Skip to content

fix: keep Final aggregate expressions in sync with a rebuilt Partial - #27827

Open
CuteChuanChuan wants to merge 1 commit into
apache:mainfrom
CuteChuanChuan:issue-27458/sync-final-aggr-exprs
Open

CuteChuanChuan wants to merge 1 commit into
apache:mainfrom
CuteChuanChuan:issue-27458/sync-final-aggr-exprs

Conversation

@CuteChuanChuan

@CuteChuanChuan CuteChuanChuan commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

nth_value(x, n ORDER BY ...) with n >= 2 returns the wrong row when the optimizer swaps the join below the aggregate. The rebuilt Partial reverses the expression to match the new input ordering, but the Final keeps the expressions it copied at planning time and reads the reversed state in the wrong direction.

What changes are included in this PR?

  • When an AggregateExec that merges partial state (Final, FinalPartitioned, PartialReduce) is rebuilt with Recompute, it walks down single-child nodes to its Partial and adopts that Partial's aggregate expressions. They are adopted only if the count and names match. Otherwise it keeps its own expressions, which is the current behavior.

What is the testing strategy for this PR?

  • Added the issue's reproducer to aggregate.slt. Query 1 returned a before this change and returns b now.

Are there any user-facing changes?

No.

@github-actions github-actions Bot added sqllogictest SQL Logic Tests (.slt) physical-plan Changes to the physical-plan crate labels Nov 28, 2026
@CuteChuanChuan

Copy link
Copy Markdown
Contributor Author

Hi @jayzhan211 ,
could you PTAL when you have a chance? Thanks! 🙏

@jayzhan211 jayzhan211 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@CuteChuanChuan thanks for picking this up! The nth_value fix works, but copying the Partial's expressions makes last_value return wrong rows on a query that main gets right, and a Final above a PartialReduce still reads reversed state. Both comments below include a tested fix and a test.

Comment on lines +3096 to +3119
/// Returns the aggregate expressions of the `Partial` [`AggregateExec`]
/// whose state `input` carries.
///
/// Rebuilding a `Partial` aggregate over a differently ordered input can
/// reverse an order-sensitive expression, which changes the layout of its
/// state. The stage that merges that state must use the same expressions.
fn find_partial_aggr_exprs(
input: &Arc<dyn ExecutionPlan>,
) -> Option<Vec<Arc<AggregateFunctionExpr>>> {
let mut plan = input;
loop {
if let Some(agg_exec) = plan.downcast_ref::<AggregateExec>() {
return if *agg_exec.mode() == AggregateMode::Partial {
Some(agg_exec.aggr_expr().to_vec())
} else {
None
};
}
match plan.children().as_slice() {
[child] => plan = child,
_ => return None,
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copying the Partial's expressions also copies settings that only hold for the Partial's input, so last_value(x ORDER BY ts) now returns an arbitrary row when the join output is already sorted by ts: 192, 128 or 320 instead of 500 on the query below, while the last release returns 500. OptimizeAggregateOrder marks the Partial's last_value with with_beneficial_ordering(true), the Final adopts it on its next rebuild, and LastValueAccumulator::merge_batch then keeps whichever partition's state arrives last instead of comparing orderings. Taking only the direction from the Partial avoids this, and following the nearest PartialReduce also covers the third stage (separate comment):

Suggested change
/// Returns the aggregate expressions of the `Partial` [`AggregateExec`]
/// whose state `input` carries.
///
/// Rebuilding a `Partial` aggregate over a differently ordered input can
/// reverse an order-sensitive expression, which changes the layout of its
/// state. The stage that merges that state must use the same expressions.
fn find_partial_aggr_exprs(
input: &Arc<dyn ExecutionPlan>,
) -> Option<Vec<Arc<AggregateFunctionExpr>>> {
let mut plan = input;
loop {
if let Some(agg_exec) = plan.downcast_ref::<AggregateExec>() {
return if *agg_exec.mode() == AggregateMode::Partial {
Some(agg_exec.aggr_expr().to_vec())
} else {
None
};
}
match plan.children().as_slice() {
[child] => plan = child,
_ => return None,
}
}
}
/// Reverses each of `aggr_expr` whose counterpart in the aggregate that
/// produced the state in `input` is the same function, reversed.
///
/// Rebuilding a first-stage aggregate over a differently ordered input can
/// reverse an order-sensitive expression, which changes the layout of its
/// state (#27458). Only the direction is taken from the producer: its
/// expressions can also carry settings that hold only for its own input,
/// such as `with_beneficial_ordering`, which makes `last_value` skip the
/// ordering comparison in `merge_batch`.
fn match_state_direction(
aggr_expr: &[Arc<AggregateFunctionExpr>],
input: &Arc<dyn ExecutionPlan>,
) -> Vec<Arc<AggregateFunctionExpr>> {
let Some(producer) = find_state_producer(input) else {
return aggr_expr.to_vec();
};
let producer = producer.aggr_expr();
if producer.len() != aggr_expr.len() {
return aggr_expr.to_vec();
}
aggr_expr
.iter()
.zip(producer)
.map(|(expr, produced)| {
// `first_value` and `last_value` reverse into each other and merge
// their state by comparing orderings, so they need no sync; turning
// the Final into the other function would also rename its output.
if expr.is_reversed() == produced.is_reversed()
|| expr.fun().name() != produced.fun().name()
{
return Arc::clone(expr);
}
expr.reverse_expr()
.map_or_else(|| Arc::clone(expr), Arc::new)
})
.collect()
}
/// Returns the nearest [`AggregateExec`] below `input`, following single-child
/// nodes, if it outputs partial state (`Partial` or `PartialReduce`).
fn find_state_producer(input: &Arc<dyn ExecutionPlan>) -> Option<&AggregateExec> {
let mut plan = input;
loop {
if let Some(agg_exec) = plan.downcast_ref::<AggregateExec>() {
return (agg_exec.mode().output_mode() == AggregateOutputMode::Partial)
.then_some(agg_exec);
}
match plan.children().as_slice() {
[child] => plan = child,
_ => return None,
}
}
}

And in replace_children:

                 let aggr_expr = match self.mode.input_mode() {
-                    AggregateInputMode::Partial => find_partial_aggr_exprs(&children[0])
-                        .filter(|partial| {
-                            partial.len() == self.aggr_expr().len()
-                                && partial
-                                    .iter()
-                                    .zip(self.aggr_expr())
-                                    .all(|(p, c)| p.name() == c.name())
-                        }),
-                    AggregateInputMode::Raw => None,
-                }
-                .unwrap_or_else(|| self.aggr_expr().to_vec());
+                    AggregateInputMode::Partial => {
+                        match_state_direction(self.aggr_expr(), &children[0])
+                    }
+                    AggregateInputMode::Raw => self.aggr_expr().to_vec(),
+                };

With this, your two queries and the one below pass, along with the full sqllogictest suite and cargo test -p datafusion-physical-plan. Could you add the test below to aggregate.slt? It fails 18 of 20 runs on this PR's head and passes 20 of 20 on main and with the change above.

sqllogictest: last_value over a join already sorted by the ORDER BY
# The Final must not take the Partial's pre-ordered last_value.
statement ok
set datafusion.execution.batch_size = 8;

statement ok
set datafusion.execution.target_partitions = 16;

query I
COPY (SELECT value::int AS ts, CAST(value AS VARCHAR) AS x FROM generate_series(1, 2000) ORDER BY value)
TO 'test_files/scratch/aggregate/lv_r.parquet'
STORED AS PARQUET;
----
2000

query I
COPY (SELECT value::int AS k FROM generate_series(0, 500) ORDER BY value DESC)
TO 'test_files/scratch/aggregate/lv_l.parquet'
STORED AS PARQUET;
----
501

statement ok
CREATE EXTERNAL TABLE lv_r (ts INT, x VARCHAR)
STORED AS PARQUET
WITH ORDER (ts ASC)
LOCATION 'test_files/scratch/aggregate/lv_r.parquet';

statement ok
CREATE EXTERNAL TABLE lv_l (k INT)
STORED AS PARQUET
WITH ORDER (k DESC)
LOCATION 'test_files/scratch/aggregate/lv_l.parquet';

query TT
SELECT first_value(lv_r.x ORDER BY lv_r.ts), last_value(lv_r.x ORDER BY lv_r.ts)
FROM lv_r JOIN lv_l ON lv_l.k = lv_r.ts;
----
1 500

statement ok
DROP TABLE lv_r;

statement ok
DROP TABLE lv_l;

statement ok
reset datafusion.execution.batch_size;

statement ok
set datafusion.execution.target_partitions = 4;

let mut plan = input;
loop {
if let Some(agg_exec) = plan.downcast_ref::<AggregateExec>() {
return if *agg_exec.mode() == AggregateMode::Partial {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The walk stops at the first AggregateExec and only accepts AggregateMode::Partial, so a Final above a PartialReduce keeps the unreversed nth_value and returns 10 instead of 20 in the test below. The PR description lists PartialReduce as covered, and its state comes from the same reversed Partial. Checking agg_exec.mode().output_mode() == AggregateOutputMode::Partial fixes it; the suggestion in the other comment includes that change. Could you add this test to aggregates/mod.rs? It fails on this head and passes with that change.

Unit test: Final over PartialReduce follows a reversed Partial
    /// A `Final` above a `PartialReduce` must follow a `Partial` that
    /// reversed `nth_value` after the input ordering changed (#27458).
    #[tokio::test]
    async fn final_over_partial_reduce_follows_reversed_partial() -> Result<()> {
        use crate::execution_plan::replace_children_if_necessary;
        use datafusion_functions_aggregate::nth_value::nth_value_udaf;

        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int64, false),
            Field::new("b", DataType::Int64, false),
        ]));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int64Array::from(vec![30, 20, 10])),
                Arc::new(Int64Array::from(vec![3, 2, 1])),
            ],
        )?;
        let input_sorted_by_b = |descending: bool| -> Result<Arc<dyn ExecutionPlan>> {
            let ordering = LexOrdering::new([PhysicalSortExpr::new(
                col("b", &schema)?,
                SortOptions::new(descending, false),
            )])
            .unwrap();
            let input = TestMemoryExec::try_new(
                &[vec![batch.clone()]],
                Arc::clone(&schema),
                None,
            )?
            .try_with_sort_information(vec![ordering])?;
            Ok(Arc::new(TestMemoryExec::update_cache(&Arc::new(input))))
        };
        // nth_value(a, 2 ORDER BY b ASC)
        let aggr = vec![Arc::new(
            AggregateExprBuilder::new(
                nth_value_udaf(),
                vec![col("a", &schema)?, lit(2i64)],
            )
            .order_by(vec![PhysicalSortExpr::new(
                col("b", &schema)?,
                SortOptions::new(false, false),
            )])
            .schema(Arc::clone(&schema))
            .alias("nth")
            .build()?,
        )];
        let group_by = PhysicalGroupBy::new_single(vec![]);
        let new_agg =
            |mode, input: Arc<dyn ExecutionPlan>| -> Result<Arc<dyn ExecutionPlan>> {
                let group_by = if mode == AggregateMode::Partial {
                    group_by.clone()
                } else {
                    group_by.as_final()
                };
                Ok(Arc::new(AggregateExec::try_new(
                    mode,
                    group_by,
                    aggr.clone(),
                    vec![None],
                    input,
                    Arc::clone(&schema),
                )?))
            };
        let partial = new_agg(AggregateMode::Partial, input_sorted_by_b(false)?)?;
        let reduce = new_agg(AggregateMode::PartialReduce, Arc::clone(&partial))?;
        let final_agg = new_agg(AggregateMode::Final, Arc::clone(&reduce))?;

        // Rebuild bottom-up over input sorted by `b DESC`, as an optimizer
        // rule that swaps a join below the aggregate does.
        let partial =
            replace_children_if_necessary(partial, vec![input_sorted_by_b(true)?])?;
        let reduce = replace_children_if_necessary(reduce, vec![partial])?;
        let final_agg = replace_children_if_necessary(final_agg, vec![reduce])?;

        let batches = crate::collect(final_agg, Arc::new(TaskContext::default())).await?;
        assert_snapshot!(batches_to_string(&batches), @r"
        +-----+
        | nth |
        +-----+
        | 20  |
        +-----+
        ");
        Ok(())
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

physical-plan Changes to the physical-plan crate sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

nth_value(x, n ORDER BY ...) returns the wrong row when the join below the aggregate is swapped

2 participants