You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/10/07 13:16:38 UTC
(datafusion) branch gh-readonly-queue/main/pr-25400-549439f50aa49bece7214cfaf4cb5d81f8d50134 created (now 9fb986ca13)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a change to branch gh-readonly-queue/main/pr-25400-549439f50aa49bece7214cfaf4cb5d81f8d50134
in repository https://gitbox.apache.org/repos/asf/datafusion.git
at 9fb986ca13 fix: ignore repeated sort keys in an ordered aggregate's ORDER BY (#25400)
This branch includes the following new commits:
new 9fb986ca13 fix: ignore repeated sort keys in an ordered aggregate's ORDER BY (#25400)
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org
(datafusion) 01/01: fix: ignore repeated sort keys in an ordered aggregate's ORDER BY (#25400)
Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-25400-549439f50aa49bece7214cfaf4cb5d81f8d50134
in repository https://gitbox.apache.org/repos/asf/datafusion.git
commit 9fb986ca132881f3ee4c14f52e33b526adf82ec7
Author: Muhammad Hassaan <12...@users.noreply.github.com>
AuthorDate: Wed Oct 7 13:16:14 2026 +0000
fix: ignore repeated sort keys in an ordered aggregate's ORDER BY (#25400)
## Which issue does this PR close?
- Closes #25398.
## Rationale for this change
If an ordered aggregate's `ORDER BY` names the same expression more than
once, the query panics or fails with an internal Arrow error:
```sql
CREATE TABLE t AS SELECT i % 3 AS b, i AS id FROM (SELECT unnest(range(0,10)) AS i);
SELECT b, first_value(id ORDER BY b, b) FROM t GROUP BY b;
-- panicked at datafusion/functions-aggregate/src/first_last.rs:602:13
-- assertion `left == right` failed left: 2 right: 1
```
Repeating a key is legal SQL. `DISTINCT ON` is the easy way to hit this
by accident, because its key has to lead the `ORDER BY`, and writing the
key out again produces the duplicate: `SELECT DISTINCT ON (b) b FROM t
ORDER BY b, b`.
The two sides of the ordered aggregate count the sort keys differently:
- `AggregateExprBuilder::build` derives the ordering state fields
(`ordering_fields`) from the `ORDER BY` list as written, so `b, b`
becomes two fields.
- Every accumulator (`first_value`, `last_value`, `nth_value`,
`array_agg`, `string_agg`) builds its ordering with `LexOrdering::new`,
which drops a sort key whose expression already appeared, so `b, b`
becomes one key.
Depending on which consumer compares them first, the mismatch shows up
as the `first_last.rs` assertion, `Incorrect number of arrays provided
to RowConverter`, or a column-count mismatch in the state schema.
## What changes are included in this PR?
`AggregateExprBuilder::build` now passes `order_bys` through
`LexOrdering` before deriving the ordering types and fields. The state
and the accumulators then agree on the number of sort keys.
A repeated key can never break a tie the earlier one left, so dropping
it doesn't change results. As with `LexOrdering` elsewhere, the first
occurrence wins, so `ORDER BY b ASC, b DESC` orders like `ORDER BY b
ASC`.
## What is the testing strategy for this PR?
A new block in `aggregate.slt` next to the existing ordered `string_agg`
tests. Its table has a unique sort key, so each expected value is
decided by the ordering, not by a tie. It covers:
- `first_value`, `last_value` and `nth_value`, with `nth_value` using an
expression key (`k + 0, k + 0`)
- `array_agg`, plus `string_agg` with `ORDER BY k DESC, k ASC`
- `DISTINCT ON (g) ... ORDER BY g, g, k`
Without the change, three of the new queries fail: the two panics and
the RowConverter error from the issue. With it, they pass. The other
`.slt` files that exercise ordered aggregates (`aggregate`, `array_agg`,
`group_by`, `first_last_*`, `distinct_on`, `window`, `order`,
`subquery_sort`) still pass.
I also ran every query in the issue's matrix and compared it with the
same query with the repeated key removed. All twelve return the same
rows.
## Are there any user-facing changes?
Queries that failed now return results. No API changes.
## Notes for reviewers
- **`min`/`max` are no longer part of this.** The schema mismatch they
hit was a separate bug, fixed by #25402 (merged). This PR is the
duplicate-sort-key fix on top of it: `build()` now clears the ORDER BY
for an order-insensitive aggregate, and otherwise drops repeated sort
keys.
- **`with_new_expressions` rebuilds `order_bys` by zipping the existing
keys with new expressions.** In principle a rewrite could map two
distinct sort keys onto the same expression and reintroduce a repeat.
Checking the callers, the only production one that passes the order-by
list is the physical planner (`core/src/physical_planner.rs`), and it
passes the keys back unchanged; the window sliding-aggregate caller
passes an empty list. Thanks to @haochunchang for independently going
through these.
---
datafusion/physical-expr/src/aggregate.rs | 14 +++++--
datafusion/sqllogictest/test_files/aggregate.slt | 49 ++++++++++++++++++++++++
2 files changed, 59 insertions(+), 4 deletions(-)
diff --git a/datafusion/physical-expr/src/aggregate.rs b/datafusion/physical-expr/src/aggregate.rs
index 6d95d8ea12..7b72a2622a 100644
--- a/datafusion/physical-expr/src/aggregate.rs
+++ b/datafusion/physical-expr/src/aggregate.rs
@@ -61,7 +61,7 @@ use datafusion_functions_aggregate_common::accumulator::{
};
use datafusion_functions_aggregate_common::order::AggregateOrderSensitivity;
use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
-use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
+use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
#[derive(Debug, Clone)]
struct AggregateHumanDisplay {
@@ -265,12 +265,18 @@ impl AggregateExprBuilder {
assert_or_internal_err!(!args.is_empty(), "args should not be empty");
// An order-insensitive aggregate ignores its ORDER BY, so drop it here.
- // Everything derived from `order_bys` below, such as the ordering fields
- // in the aggregate's state, then agrees that there is no ordering.
+ // Otherwise drop sort keys that repeat an earlier one: a repeated key can
+ // never break a tie the earlier one left (`ORDER BY b ASC, b DESC` orders
+ // like `ORDER BY b ASC`), and accumulators build their ordering with
+ // `LexOrdering`, which drops such repeats. Everything derived from
+ // `order_bys` below, such as the ordering fields in the aggregate's
+ // state, then matches the sort keys the accumulators compare.
let order_bys = if fun.order_sensitivity().is_insensitive() {
vec![]
} else {
- order_bys
+ LexOrdering::new(order_bys)
+ .map(Vec::from)
+ .unwrap_or_default()
};
let ordering_types = order_bys
diff --git a/datafusion/sqllogictest/test_files/aggregate.slt b/datafusion/sqllogictest/test_files/aggregate.slt
index ac0331975b..a9ede1b1b4 100644
--- a/datafusion/sqllogictest/test_files/aggregate.slt
+++ b/datafusion/sqllogictest/test_files/aggregate.slt
@@ -8230,6 +8230,55 @@ c,a,b,d d,b,a,c
statement ok
drop table t;
+# A sort key repeated in an ordered aggregate's ORDER BY is redundant, and the
+# query must behave as if the key were listed once (issue #25398). Each `k` is
+# unique so every expected value is determined by the ordering.
+statement ok
+CREATE TABLE dup_sort_keys (g INT, k INT, v INT) AS VALUES
+ (1, 2, 20), (1, 1, 10), (2, 4, 40), (2, 3, 30);
+
+query IIII
+SELECT g,
+ first_value(v ORDER BY k, k),
+ last_value(v ORDER BY k, k),
+ nth_value(v, 2 ORDER BY k + 0, k + 0)
+FROM dup_sort_keys GROUP BY g ORDER BY g;
+----
+1 10 20 20
+2 30 40 40
+
+query I?T
+SELECT g,
+ array_agg(v ORDER BY k, k),
+ string_agg(CAST(v AS VARCHAR), ',' ORDER BY k DESC, k ASC)
+FROM dup_sort_keys GROUP BY g ORDER BY g;
+----
+1 [10, 20] 20,10
+2 [30, 40] 40,30
+
+# With DISTINCT, the ORDER BY may only sort by the aggregated expression. The
+# repeated key is dropped first, so these are accepted.
+query I?
+SELECT g, array_agg(DISTINCT k ORDER BY k, k) FROM dup_sort_keys GROUP BY g ORDER BY g;
+----
+1 [1, 2]
+2 [3, 4]
+
+query I?
+SELECT g, array_agg(DISTINCT k ORDER BY k DESC, k ASC) FROM dup_sort_keys GROUP BY g ORDER BY g;
+----
+1 [2, 1]
+2 [4, 3]
+
+query II
+SELECT DISTINCT ON (g) g, v FROM dup_sort_keys ORDER BY g, g, k;
+----
+1 10
+2 30
+
+statement ok
+drop table dup_sort_keys;
+
# Tests for aggregating with NaN values
statement ok
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org