Skip to content

Commit e8f0e7d

Browse files
xavleeTristan1900
authored andcommitted
feat: add grouping equivalence properties (apache#24698)
## Which issue does this PR relate to? - Part of apache#24438. - Builds on apache#24737 and apache#24697, both merged. ## Rationale for this change Aggregation can recognize completed groups when all rows with the same grouping-key tuple occur in one contiguous run within a partition. Sorted input provides this guarantee, and the runs can also appear in an arbitrary order: ```text AAABBBCCCC -> ordered and grouped CCCAAABBB -> grouped; each group can be completed when its run ends AAABBBAACC -> A appears in separate runs ``` This PR represents that guarantee in `EquivalenceProperties`, allowing execution-plan producers to declare grouping tuples and consumers to check whether an input satisfies a grouping requirement. ## What changes are included in this PR? ### Semantics and propagation A grouping assertion describes a complete expression tuple within every output partition. `[a, b]` and `[b, a]` identify the same groups. The guarantee applies to the complete pair; a guarantee for a subset such as `[a]` requires its own proof. Grouping assertions are correctness guarantees supplied by producers. DataFusion trusts the asserted row layout. Producers can declare derived tuples such as `[bhandle, date_bin(timestamp)]` directly. - Store grouping tuples alongside ordering, equality, and constant information in `EquivalenceProperties`. - Normalize tuples using expression equivalences and constants, removing duplicate expressions. - Check grouping requirements against declared tuples and grouping implied by lexicographical ordering prefixes. - Project a tuple when every expression can be represented in the output, including explicitly declared derived expressions. - Remap grouping expressions during schema replacement. - Preserve a declared grouping tuple through `UnionExec` when every input satisfies it, explicitly or through ordering. - Clear explicit grouping assertions at aggregation, sorting, repartitioning, and partition-merging boundaries where execution can invalidate them. ### Public API additions - `GroupingEquivalenceClass` represents complete grouping tuples and supports construction, insertion, lookup, clearing, schema rewriting, iteration, and display. - `EquivalenceProperties::{geq_class, normalized_geq_class, add_grouping, add_groupings, clear_groupings, grouping_satisfy}` expose grouping metadata and its analysis. - `TestMemoryExec::try_with_grouping_information` attaches grouping assertions in physical-plan tests and examples. Execution-plan producers attach these assertions through the `EquivalenceProperties` held by `PlanProperties`. The follow-up apache#24497 consumes them to derive `GroupClusteringMode::Full` for eligible aggregates. ## Stack 1. [apache#24737 — test: cover unsorted contiguous groups in one partition](apache#24737) (merged) 2. [apache#24697 — refactor: use group clustering terminology in aggregate execution](apache#24697) (merged) 3. [apache#24698 — feat: add grouping equivalence properties](apache#24698) ← **this PR** 4. [apache#24497 — feat: stream aggregates over grouped input](apache#24497) ## What is the testing strategy for this PR? Tests cover complete-tuple semantics, equivalent permutations, normalization through equivalences and constants, ordering-derived grouping, complete and incomplete projection mappings, explicitly declared derived expressions, operator boundaries, and UNION propagation with selective tuple retention, mixed grouping/ordering proofs, schema rewrites, and input permutations. `aggregate_clears_explicit_grouping` covers partial and single aggregation with reordered and aliased grouping keys. Both cases fail without the aggregate boundary clear and pass with it. Local validation passed the extended workspace suite, including 2,997 physical-plan tests and 546 SQL logic files, and all-target/all-feature Clippy with warnings denied. ## Are there any user-facing changes? Yes. The additive Rust APIs above let plan producers describe contiguous grouping tuples and let consumers evaluate grouping requirements. The streaming aggregate optimization follows in apache#24497. ## Review this layer [View this PR's diff](https://github.com/apache/datafusion/pull/24698/files) (cherry picked from commit 320a7d2)
1 parent f77118c commit e8f0e7d

12 files changed

Lines changed: 1090 additions & 39 deletions

File tree

‎datafusion/ffi/src/session/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -976,7 +976,7 @@ mod tests {
976976
let physical_plan = foreign_session.create_physical_plan(&logical_plan).await?;
977977
assert_eq!(
978978
format!("{physical_plan:?}"),
979-
"EmptyExec { schema: Schema { fields: [], metadata: {} }, partitions: 1, cache: PlanProperties { eq_properties: EquivalenceProperties { eq_group: EquivalenceGroup { map: {}, classes: [] }, oeq_class: OrderingEquivalenceClass { orderings: [] }, oeq_cache: OrderingEquivalenceCache { normal_cls: OrderingEquivalenceClass { orderings: [] }, leading_map: {} }, constraints: Constraints { inner: [] }, schema: Schema { fields: [], metadata: {} } }, partitioning: UnknownPartitioning(1), emission_type: Incremental, boundedness: Bounded, evaluation_type: Lazy, scheduling_type: Cooperative, output_ordering: None } }"
979+
"EmptyExec { schema: Schema { fields: [], metadata: {} }, partitions: 1, cache: PlanProperties { eq_properties: EquivalenceProperties { eq_group: EquivalenceGroup { map: {}, classes: [] }, oeq_class: OrderingEquivalenceClass { orderings: [] }, geq_class: GroupingEquivalenceClass { groupings: [] }, oeq_cache: OrderingEquivalenceCache { normal_cls: OrderingEquivalenceClass { orderings: [] }, leading_map: {} }, geq_cache: GroupingEquivalenceClass { groupings: [] }, constraints: Constraints { inner: [] }, schema: Schema { fields: [], metadata: {} } }, partitioning: UnknownPartitioning(1), emission_type: Incremental, boundedness: Bounded, evaluation_type: Lazy, scheduling_type: Cooperative, output_ordering: None } }"
980980
);
981981

982982
assert_eq!(
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
use std::fmt::Display;
19+
use std::ops::Deref;
20+
use std::sync::Arc;
21+
use std::vec::IntoIter;
22+
23+
use crate::PhysicalExpr;
24+
use crate::expressions::with_new_schema;
25+
26+
use arrow::datatypes::SchemaRef;
27+
use datafusion_common::{HashSet, Result};
28+
use datafusion_physical_expr_common::physical_expr::format_physical_expr_list;
29+
30+
/// A set of grouping tuples that are known to describe contiguous rows.
31+
///
32+
/// Each entry is a complete grouping tuple. For example, `[a, b]` means that,
33+
/// within each output partition, all rows having the same values for both `a`
34+
/// and `b` occur in one contiguous run. The runs themselves may occur in any
35+
/// order. Contiguity applies to the complete partition stream, not separately
36+
/// to each record batch.
37+
///
38+
/// Expression order within an entry is not significant: `[a, b]` and `[b, a]`
39+
/// describe the same grouping. Entries do not imply properties for subsets;
40+
/// `[a, b]` alone says nothing about whether all rows with the same `a` are
41+
/// contiguous.
42+
#[derive(Clone, Debug, Default)]
43+
pub struct GroupingEquivalenceClass {
44+
groupings: Vec<Vec<Arc<dyn PhysicalExpr>>>,
45+
}
46+
47+
impl GroupingEquivalenceClass {
48+
/// Clears all groupings in this equivalence class.
49+
pub fn clear(&mut self) {
50+
self.groupings.clear();
51+
}
52+
53+
/// Creates a grouping equivalence class, discarding empty and duplicate
54+
/// entries and duplicate expressions within each entry.
55+
pub fn new(
56+
groupings: impl IntoIterator<Item = impl IntoIterator<Item = Arc<dyn PhysicalExpr>>>,
57+
) -> Self {
58+
let mut result = Self::default();
59+
result.add_groupings(groupings);
60+
result
61+
}
62+
63+
/// Adds grouping tuples to this equivalence class.
64+
pub fn add_groupings(
65+
&mut self,
66+
groupings: impl IntoIterator<Item = impl IntoIterator<Item = Arc<dyn PhysicalExpr>>>,
67+
) {
68+
for grouping in groupings {
69+
let mut seen = HashSet::new();
70+
let grouping = grouping
71+
.into_iter()
72+
.filter(|expr| seen.insert(Arc::clone(expr)))
73+
.collect::<Vec<_>>();
74+
if !grouping.is_empty() && !self.contains(&grouping) {
75+
self.groupings.push(grouping);
76+
}
77+
}
78+
}
79+
80+
/// Returns whether this class contains the complete grouping tuple.
81+
pub fn contains(&self, grouping: &[Arc<dyn PhysicalExpr>]) -> bool {
82+
self.groupings
83+
.iter()
84+
.any(|candidate| same_grouping(candidate, grouping))
85+
}
86+
87+
/// Rewrites all expressions to reference an aligned schema.
88+
pub fn with_new_schema(self, schema: &SchemaRef) -> Result<Self> {
89+
let groupings = self.groupings.into_iter().map(|grouping| {
90+
grouping
91+
.into_iter()
92+
.map(|expr| with_new_schema(expr, schema))
93+
.collect::<Result<Vec<_>>>()
94+
});
95+
Ok(Self::new(groupings.collect::<Result<Vec<_>>>()?))
96+
}
97+
}
98+
99+
fn same_grouping(lhs: &[Arc<dyn PhysicalExpr>], rhs: &[Arc<dyn PhysicalExpr>]) -> bool {
100+
lhs.iter()
101+
.all(|lhs_expr| rhs.iter().any(|rhs_expr| lhs_expr.eq(rhs_expr)))
102+
&& rhs
103+
.iter()
104+
.all(|rhs_expr| lhs.iter().any(|lhs_expr| rhs_expr.eq(lhs_expr)))
105+
}
106+
107+
impl PartialEq for GroupingEquivalenceClass {
108+
fn eq(&self, other: &Self) -> bool {
109+
self.groupings.len() == other.groupings.len()
110+
&& self
111+
.groupings
112+
.iter()
113+
.all(|grouping| other.contains(grouping))
114+
}
115+
}
116+
117+
impl Eq for GroupingEquivalenceClass {}
118+
119+
impl Deref for GroupingEquivalenceClass {
120+
type Target = [Vec<Arc<dyn PhysicalExpr>>];
121+
122+
fn deref(&self) -> &Self::Target {
123+
self.groupings.as_slice()
124+
}
125+
}
126+
127+
impl From<Vec<Vec<Arc<dyn PhysicalExpr>>>> for GroupingEquivalenceClass {
128+
fn from(groupings: Vec<Vec<Arc<dyn PhysicalExpr>>>) -> Self {
129+
Self::new(groupings)
130+
}
131+
}
132+
133+
/// Converts the grouping equivalence class into an iterator of complete
134+
/// grouping tuples.
135+
impl IntoIterator for GroupingEquivalenceClass {
136+
type Item = Vec<Arc<dyn PhysicalExpr>>;
137+
type IntoIter = IntoIter<Self::Item>;
138+
139+
fn into_iter(self) -> Self::IntoIter {
140+
self.groupings.into_iter()
141+
}
142+
}
143+
144+
impl From<GroupingEquivalenceClass> for Vec<Vec<Arc<dyn PhysicalExpr>>> {
145+
fn from(geq_class: GroupingEquivalenceClass) -> Self {
146+
geq_class.groupings
147+
}
148+
}
149+
150+
impl Display for GroupingEquivalenceClass {
151+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152+
write!(f, "[")?;
153+
let mut groupings = self.groupings.iter();
154+
if let Some(grouping) = groupings.next() {
155+
write!(f, "{}", format_physical_expr_list(grouping))?;
156+
}
157+
for grouping in groupings {
158+
write!(f, ", {}", format_physical_expr_list(grouping))?;
159+
}
160+
write!(f, "]")
161+
}
162+
}
163+
164+
#[cfg(test)]
165+
mod tests {
166+
use super::*;
167+
use crate::expressions::Column;
168+
169+
#[test]
170+
fn grouping_equality_ignores_expression_and_entry_order() {
171+
let a = Arc::new(Column::new("a", 0)) as Arc<dyn PhysicalExpr>;
172+
let b = Arc::new(Column::new("b", 1)) as Arc<dyn PhysicalExpr>;
173+
let c = Arc::new(Column::new("c", 2)) as Arc<dyn PhysicalExpr>;
174+
175+
let lhs = GroupingEquivalenceClass::new([
176+
vec![Arc::clone(&a), Arc::clone(&b)],
177+
vec![Arc::clone(&c)],
178+
]);
179+
let rhs = GroupingEquivalenceClass::new([
180+
vec![Arc::clone(&c)],
181+
vec![Arc::clone(&b), Arc::clone(&a)],
182+
]);
183+
184+
assert_eq!(lhs, rhs);
185+
// The same expressions in different tuples describe different guarantees.
186+
assert_ne!(lhs, GroupingEquivalenceClass::new([vec![a, c], vec![b]]));
187+
}
188+
189+
#[test]
190+
fn grouping_deduplicates_entries_and_expressions() {
191+
let a = Arc::new(Column::new("a", 0)) as Arc<dyn PhysicalExpr>;
192+
let b = Arc::new(Column::new("b", 1)) as Arc<dyn PhysicalExpr>;
193+
194+
let groupings = GroupingEquivalenceClass::new([
195+
vec![Arc::clone(&a), Arc::clone(&a), Arc::clone(&b)],
196+
vec![Arc::clone(&b), Arc::clone(&a)],
197+
vec![],
198+
]);
199+
200+
assert_eq!(groupings.len(), 1);
201+
assert_eq!(groupings[0].len(), 2);
202+
assert!(groupings.contains(&[Arc::clone(&a), Arc::clone(&a), Arc::clone(&b),]));
203+
assert_eq!(groupings.to_string(), "[[a@0, b@1]]");
204+
}
205+
}

0 commit comments

Comments
 (0)