jayzhan211 commented on code in PR #27827:
URL: https://github.com/apache/datafusion/pull/27827#discussion_r4729608599
##########
datafusion/physical-plan/src/aggregates/mod.rs:
##########
@@ -3081,6 +3093,31 @@ fn determine_finer(
}
}
+/// 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,
+ }
+ }
+}
Review Comment:
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):
```suggestion
/// 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`:
```diff
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.
<details>
<summary>sqllogictest: last_value over a join already sorted by the ORDER
BY</summary>
```
# 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;
```
</details>
##########
datafusion/physical-plan/src/aggregates/mod.rs:
##########
@@ -3081,6 +3093,31 @@ fn determine_finer(
}
}
+/// 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 {
Review Comment:
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.
<details>
<summary>Unit test: Final over PartialReduce follows a reversed
Partial</summary>
```rs
/// 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(())
}
```
</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]