Skip to content

Commit ebdb657

Browse files
authored
refactor: Make AggregateExec state modeling and public updates safe (part 1: distinct limit) (apache#25564)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123. --> - Part of apache#25563 ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. Please explain the problem you are trying to solve in terms of the user-visible behavior, rather than the implementation. For example, "The code in `foo.rs` doesn't handle nulls" is a symptom of the implementation. "COUNT(DISTINCT) returns wrong results when the column contains nulls" is the user-visible problem. --> See issue for the idea, this PR is the step 1 in the issue. For backgrounds for distinct limit optimization (this PR targets), see https://github.com/apache/datafusion/blob/1e09a2a3d76c03f469e80bed712a6bada45e77c8/datafusion/physical-plan/src/aggregates/hash_stream.rs#L77 ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here, but it is sometimes worth providing a summary of the individual changes in this PR. --> 1. Refactor AggregateExec with enum state 2. Add safe API for this optimization, and use it in the optimizer. (unsafe one will be able to be deleted after step2, now it's reused by other path) I'll mark the structural changes (only 2 files) Most diff is mechanical changes like `aggregate_exec.aggr_expr` -> `aggregate_exec.aggr_expr()`, caused by the refactor. ## What is the testing strategy for this PR? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 4. Serve as another way to document the expected behavior of the code Briefly describe how this PR is tested, and point to the specific tests you added. For example: 'This new feature is covered by the `sqllogictest` cases added in `foo.slt`'. If this PR does not add tests, explain why. For example, if the change is already covered by existing tests, please mention it. You should also check the `codecov` bot reply on this PR to confirm the changed code is exercised. --> Existing tests. ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. If there are any breaking changes to public APIs, please add the `api change` label. --> no
1 parent d5216e6 commit ebdb657

19 files changed

Lines changed: 259 additions & 169 deletions

‎datafusion/physical-optimizer/src/limited_distinct_aggregation.rs‎

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
2121
use std::sync::Arc;
2222

23-
use datafusion_physical_plan::aggregates::{AggregateExec, LimitOptions};
23+
use datafusion_physical_plan::aggregates::AggregateExec;
2424
use datafusion_physical_plan::limit::{GlobalLimitExec, LocalLimitExec};
2525
use datafusion_physical_plan::{ExecutionPlan, ExecutionPlanProperties};
2626

@@ -47,16 +47,10 @@ impl LimitedDistinctAggregation {
4747
fn transform_agg(
4848
aggr: &AggregateExec,
4949
limit: usize,
50-
) -> Option<Arc<dyn ExecutionPlan>> {
51-
// rules for transforming this Aggregate are held in this method
52-
if !aggr.is_unordered_unfiltered_group_by_distinct() {
53-
return None;
54-
}
55-
56-
// We found what we want: clone, copy the limit down, and return modified node
57-
let new_aggr = aggr.with_new_limit_options(Some(LimitOptions::new(limit)));
58-
59-
Some(Arc::new(new_aggr))
50+
) -> Option<Transformed<Arc<dyn ExecutionPlan>>> {
51+
let new_aggr = aggr.clone().try_optimize_distinct_soft_limit(limit)?;
52+
// An already limited aggregate still permits optimizing its partial child.
53+
Some(new_aggr.update_data(|aggr| Arc::new(aggr) as Arc<dyn ExecutionPlan>))
6054
}
6155

6256
/// transform_limit matches an `AggregateExec` as the child of a `LocalLimitExec`
@@ -119,14 +113,18 @@ impl LimitedDistinctAggregation {
119113
Some(new_aggr) => {
120114
match_aggr = plan;
121115
found_match_aggr = true;
122-
return Ok(Transformed::yes(new_aggr));
116+
return Ok(new_aggr);
123117
}
124118
}
125119
}
126120
rewrite_applicable = false;
127121
Ok(Transformed::no(plan))
128122
};
129-
let child = child.to_owned().transform_down(closure).data().ok()?;
123+
let child = child.to_owned().transform_down(closure).ok()?;
124+
if !child.transformed {
125+
return None;
126+
}
127+
let child = child.data;
130128
if is_global_limit {
131129
return Some(Arc::new(GlobalLimitExec::new(
132130
child,

‎datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -156,12 +156,12 @@ impl<AggrMode> AggregateHashTable<AggrMode> {
156156
let input_schema = agg.input().schema();
157157
let metrics = AggregateTableMetrics::new(agg, partition);
158158
let aggregate_arguments = aggregate_expressions(
159-
&agg.aggr_expr,
159+
agg.aggr_expr(),
160160
&agg.mode,
161-
agg.group_by.num_group_exprs(),
161+
agg.group_by().num_group_exprs(),
162162
)?;
163163
let accumulators: Vec<_> = agg
164-
.aggr_expr
164+
.aggr_expr()
165165
.iter()
166166
.zip(aggregate_arguments)
167167
.zip(filters)
@@ -179,7 +179,7 @@ impl<AggrMode> AggregateHashTable<AggrMode> {
179179
})
180180
.collect::<Result<_>>()?;
181181

182-
let group_schema = agg.group_by.group_schema(&input_schema)?;
182+
let group_schema = agg.group_by().group_schema(&input_schema)?;
183183
let group_values = new_group_values(group_schema, &GroupOrdering::None)?;
184184

185185
Ok(Self {
@@ -192,7 +192,7 @@ impl<AggrMode> AggregateHashTable<AggrMode> {
192192
state_schema,
193193
batch_size,
194194
state: AggregateHashTableState::Building(AggregateHashTableBuffer {
195-
group_by: Arc::clone(&agg.group_by),
195+
group_by: Arc::clone(agg.group_by()),
196196
group_values,
197197
batch_group_indices: Default::default(),
198198
accumulators,

‎datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_ordered.rs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -200,15 +200,15 @@ impl<AggrMode> OrderedAggregateTable<AggrMode> {
200200
);
201201

202202
let group_ordering = GroupOrdering::try_new(input_order_mode)?;
203-
let group_schema = agg.group_by.group_schema(input_schema)?;
203+
let group_schema = agg.group_by().group_schema(input_schema)?;
204204
let group_values = new_group_values(group_schema, &group_ordering)?;
205205
let aggregate_arguments = aggregate_expressions(
206-
&agg.aggr_expr,
206+
agg.aggr_expr(),
207207
aggregate_mode,
208-
agg.group_by.num_group_exprs(),
208+
agg.group_by().num_group_exprs(),
209209
)?;
210210
let accumulators = agg
211-
.aggr_expr
211+
.aggr_expr()
212212
.iter()
213213
.zip(aggregate_arguments)
214214
.zip(filters)
@@ -235,7 +235,7 @@ impl<AggrMode> OrderedAggregateTable<AggrMode> {
235235
aggregate_accumulator_metrics: metrics.accumulator,
236236
aggregate_submetrics: metrics.submetrics,
237237
buffer: OrderedAggregateTableBuffer {
238-
group_by: Arc::clone(&agg.group_by),
238+
group_by: Arc::clone(agg.group_by()),
239239
group_ordering,
240240
group_values,
241241
group_indices: vec![],

‎datafusion/physical-plan/src/aggregates/aggregate_hash_table/final_table.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ impl AggregateHashTable<FinalMarker> {
4646
output_schema,
4747
Arc::clone(&agg.input().schema()),
4848
batch_size,
49-
vec![None; agg.aggr_expr.len()],
49+
vec![None; agg.aggr_expr().len()],
5050
)
5151
}
5252

‎datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ pub(super) struct AggregateTableMetrics {
7070
impl AggregateTableMetrics {
7171
pub(super) fn new(agg: &AggregateExec, partition: usize) -> Self {
7272
let aggregate_labels = agg
73-
.aggr_expr
73+
.aggr_expr()
7474
.iter()
7575
.map(|agg_expr| aggregate_metric_label(agg_expr))
7676
.collect::<Vec<_>>();

‎datafusion/physical-plan/src/aggregates/aggregate_hash_table/ordered_final_table.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ impl OrderedAggregateTable<FinalMarker> {
5858
batch_size,
5959
input_order_mode,
6060
&AggregateMode::Final,
61-
vec![None; agg.aggr_expr.len()],
61+
vec![None; agg.aggr_expr().len()],
6262
metrics,
6363
)
6464
}

‎datafusion/physical-plan/src/aggregates/aggregate_hash_table/ordered_partial_table.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ impl OrderedAggregateTable<PartialMarker> {
7070
batch_size,
7171
&agg.input_order_mode,
7272
&AggregateMode::Partial,
73-
agg.filter_expr.iter().cloned().collect(),
73+
agg.filter_expr().to_vec(),
7474
metrics,
7575
)
7676
}

‎datafusion/physical-plan/src/aggregates/aggregate_hash_table/ordered_single_table.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ impl OrderedAggregateTable<SingleMarker> {
6161
batch_size,
6262
&agg.input_order_mode,
6363
&agg.mode,
64-
agg.filter_expr.iter().cloned().collect(),
64+
agg.filter_expr().to_vec(),
6565
metrics,
6666
)
6767
}

‎datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_reduce_table.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ impl AggregateHashTable<PartialReduceMarker> {
4040
Arc::clone(&output_schema),
4141
output_schema,
4242
batch_size,
43-
vec![None; agg.aggr_expr.len()],
43+
vec![None; agg.aggr_expr().len()],
4444
)
4545
}
4646

‎datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ impl AggregateHashTable<PartialMarker> {
5151
Arc::clone(&output_schema),
5252
output_schema,
5353
batch_size,
54-
agg.filter_expr.iter().cloned().collect(),
54+
agg.filter_expr().to_vec(),
5555
)
5656
}
5757

0 commit comments

Comments
 (0)