datafusion 41.0.0

DataFusion is an in-memory query engine that uses Apache Arrow as the memory model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//! A special-case optimizer rule that pushes limit into a grouped aggregation
//! which has no aggregate expressions or sorting requirements

use std::sync::Arc;

use crate::physical_plan::aggregates::AggregateExec;
use crate::physical_plan::limit::{GlobalLimitExec, LocalLimitExec};
use crate::physical_plan::{ExecutionPlan, ExecutionPlanProperties};

use datafusion_common::config::ConfigOptions;
use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
use datafusion_common::Result;

use datafusion_physical_optimizer::PhysicalOptimizerRule;
use itertools::Itertools;

/// An optimizer rule that passes a `limit` hint into grouped aggregations which don't require all
/// rows in the group to be processed for correctness. Example queries fitting this description are:
/// `SELECT distinct l_orderkey FROM lineitem LIMIT 10;`
/// `SELECT l_orderkey FROM lineitem GROUP BY l_orderkey LIMIT 10;`
pub struct LimitedDistinctAggregation {}

impl LimitedDistinctAggregation {
    /// Create a new `LimitedDistinctAggregation`
    pub fn new() -> Self {
        Self {}
    }

    fn transform_agg(
        aggr: &AggregateExec,
        limit: usize,
    ) -> Option<Arc<dyn ExecutionPlan>> {
        // rules for transforming this Aggregate are held in this method
        if !aggr.is_unordered_unfiltered_group_by_distinct() {
            return None;
        }

        // We found what we want: clone, copy the limit down, and return modified node
        let new_aggr = AggregateExec::try_new(
            *aggr.mode(),
            aggr.group_expr().clone(),
            aggr.aggr_expr().to_vec(),
            aggr.filter_expr().to_vec(),
            aggr.input().clone(),
            aggr.input_schema(),
        )
        .expect("Unable to copy Aggregate!")
        .with_limit(Some(limit));
        Some(Arc::new(new_aggr))
    }

    /// transform_limit matches an `AggregateExec` as the child of a `LocalLimitExec`
    /// or `GlobalLimitExec` and pushes the limit into the aggregation as a soft limit when
    /// there is a group by, but no sorting, no aggregate expressions, and no filters in the
    /// aggregation
    fn transform_limit(plan: Arc<dyn ExecutionPlan>) -> Option<Arc<dyn ExecutionPlan>> {
        let limit: usize;
        let mut global_fetch: Option<usize> = None;
        let mut global_skip: usize = 0;
        let children: Vec<Arc<dyn ExecutionPlan>>;
        let mut is_global_limit = false;
        if let Some(local_limit) = plan.as_any().downcast_ref::<LocalLimitExec>() {
            limit = local_limit.fetch();
            children = local_limit.children().into_iter().cloned().collect();
        } else if let Some(global_limit) = plan.as_any().downcast_ref::<GlobalLimitExec>()
        {
            global_fetch = global_limit.fetch();
            global_fetch?;
            global_skip = global_limit.skip();
            // the aggregate must read at least fetch+skip number of rows
            limit = global_fetch.unwrap() + global_skip;
            children = global_limit.children().into_iter().cloned().collect();
            is_global_limit = true
        } else {
            return None;
        }
        let child = children.iter().exactly_one().ok()?;
        // ensure there is no output ordering; can this rule be relaxed?
        if plan.output_ordering().is_some() {
            return None;
        }
        // ensure no ordering is required on the input
        if plan.required_input_ordering()[0].is_some() {
            return None;
        }

        // if found_match_aggr is true, match_aggr holds a parent aggregation whose group_by
        // must match that of a child aggregation in order to rewrite the child aggregation
        let mut match_aggr: Arc<dyn ExecutionPlan> = plan;
        let mut found_match_aggr = false;

        let mut rewrite_applicable = true;
        let closure = |plan: Arc<dyn ExecutionPlan>| {
            if !rewrite_applicable {
                return Ok(Transformed::no(plan));
            }
            if let Some(aggr) = plan.as_any().downcast_ref::<AggregateExec>() {
                if found_match_aggr {
                    if let Some(parent_aggr) =
                        match_aggr.as_any().downcast_ref::<AggregateExec>()
                    {
                        if !parent_aggr.group_expr().eq(aggr.group_expr()) {
                            // a partial and final aggregation with different groupings disqualifies
                            // rewriting the child aggregation
                            rewrite_applicable = false;
                            return Ok(Transformed::no(plan));
                        }
                    }
                }
                // either we run into an Aggregate and transform it, or disable the rewrite
                // for subsequent children
                match Self::transform_agg(aggr, limit) {
                    None => {}
                    Some(new_aggr) => {
                        match_aggr = plan;
                        found_match_aggr = true;
                        return Ok(Transformed::yes(new_aggr));
                    }
                }
            }
            rewrite_applicable = false;
            Ok(Transformed::no(plan))
        };
        let child = child.clone().transform_down(closure).data().ok()?;
        if is_global_limit {
            return Some(Arc::new(GlobalLimitExec::new(
                child,
                global_skip,
                global_fetch,
            )));
        }
        Some(Arc::new(LocalLimitExec::new(child, limit)))
    }
}

impl Default for LimitedDistinctAggregation {
    fn default() -> Self {
        Self::new()
    }
}

impl PhysicalOptimizerRule for LimitedDistinctAggregation {
    fn optimize(
        &self,
        plan: Arc<dyn ExecutionPlan>,
        config: &ConfigOptions,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        if config.optimizer.enable_distinct_aggregation_soft_limit {
            plan.transform_down(|plan| {
                Ok(
                    if let Some(plan) =
                        LimitedDistinctAggregation::transform_limit(plan.clone())
                    {
                        Transformed::yes(plan)
                    } else {
                        Transformed::no(plan)
                    },
                )
            })
            .data()
        } else {
            Ok(plan)
        }
    }

    fn name(&self) -> &str {
        "LimitedDistinctAggregation"
    }

    fn schema_check(&self) -> bool {
        true
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::physical_optimizer::enforce_distribution::tests::{
        parquet_exec_with_sort, schema, trim_plan_display,
    };
    use crate::physical_plan::aggregates::PhysicalGroupBy;
    use crate::physical_plan::collect;
    use crate::physical_plan::memory::MemoryExec;
    use crate::prelude::SessionContext;
    use crate::test_util::TestAggregate;

    use arrow::array::Int32Array;
    use arrow::compute::SortOptions;
    use arrow::datatypes::{DataType, Field, Schema};
    use arrow::record_batch::RecordBatch;
    use arrow::util::pretty::pretty_format_batches;
    use arrow_schema::SchemaRef;
    use datafusion_execution::config::SessionConfig;
    use datafusion_expr::Operator;
    use datafusion_physical_expr::expressions::{cast, col};
    use datafusion_physical_expr::{expressions, PhysicalExpr, PhysicalSortExpr};
    use datafusion_physical_plan::aggregates::AggregateMode;
    use datafusion_physical_plan::displayable;

    fn mock_data() -> Result<Arc<MemoryExec>> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, true),
            Field::new("b", DataType::Int32, true),
        ]));

        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int32Array::from(vec![
                    Some(1),
                    Some(2),
                    None,
                    Some(1),
                    Some(4),
                    Some(5),
                ])),
                Arc::new(Int32Array::from(vec![
                    Some(1),
                    None,
                    Some(6),
                    Some(2),
                    Some(8),
                    Some(9),
                ])),
            ],
        )?;

        Ok(Arc::new(MemoryExec::try_new(
            &[vec![batch]],
            Arc::clone(&schema),
            None,
        )?))
    }

    fn assert_plan_matches_expected(
        plan: &Arc<dyn ExecutionPlan>,
        expected: &[&str],
    ) -> Result<()> {
        let expected_lines: Vec<&str> = expected.to_vec();
        let session_ctx = SessionContext::new();
        let state = session_ctx.state();

        let optimized = LimitedDistinctAggregation::new()
            .optimize(Arc::clone(plan), state.config_options())?;

        let optimized_result = displayable(optimized.as_ref()).indent(true).to_string();
        let actual_lines = trim_plan_display(&optimized_result);

        assert_eq!(
            &expected_lines, &actual_lines,
            "\n\nexpected:\n\n{:#?}\nactual:\n\n{:#?}\n\n",
            expected_lines, actual_lines
        );

        Ok(())
    }

    async fn assert_results_match_expected(
        plan: Arc<dyn ExecutionPlan>,
        expected: &str,
    ) -> Result<()> {
        let cfg = SessionConfig::new().with_target_partitions(1);
        let ctx = SessionContext::new_with_config(cfg);
        let batches = collect(plan, ctx.task_ctx()).await?;
        let actual = format!("{}", pretty_format_batches(&batches)?);
        assert_eq!(actual, expected);
        Ok(())
    }

    pub fn build_group_by(
        input_schema: &SchemaRef,
        columns: Vec<String>,
    ) -> PhysicalGroupBy {
        let mut group_by_expr: Vec<(Arc<dyn PhysicalExpr>, String)> = vec![];
        for column in columns.iter() {
            group_by_expr.push((col(column, input_schema).unwrap(), column.to_string()));
        }
        PhysicalGroupBy::new_single(group_by_expr.clone())
    }

    #[tokio::test]
    async fn test_partial_final() -> Result<()> {
        let source = mock_data()?;
        let schema = source.schema();

        // `SELECT a FROM MemoryExec GROUP BY a LIMIT 4;`, Partial/Final AggregateExec
        let partial_agg = AggregateExec::try_new(
            AggregateMode::Partial,
            build_group_by(&schema.clone(), vec!["a".to_string()]),
            vec![],         /* aggr_expr */
            vec![],         /* filter_expr */
            source,         /* input */
            schema.clone(), /* input_schema */
        )?;
        let final_agg = AggregateExec::try_new(
            AggregateMode::Final,
            build_group_by(&schema.clone(), vec!["a".to_string()]),
            vec![],                /* aggr_expr */
            vec![],                /* filter_expr */
            Arc::new(partial_agg), /* input */
            schema.clone(),        /* input_schema */
        )?;
        let limit_exec = LocalLimitExec::new(
            Arc::new(final_agg),
            4, // fetch
        );
        // expected to push the limit to the Partial and Final AggregateExecs
        let expected = [
            "LocalLimitExec: fetch=4",
            "AggregateExec: mode=Final, gby=[a@0 as a], aggr=[], lim=[4]",
            "AggregateExec: mode=Partial, gby=[a@0 as a], aggr=[], lim=[4]",
            "MemoryExec: partitions=1, partition_sizes=[1]",
        ];
        let plan: Arc<dyn ExecutionPlan> = Arc::new(limit_exec);
        assert_plan_matches_expected(&plan, &expected)?;
        let expected = r#"
+---+
| a |
+---+
| 1 |
| 2 |
|   |
| 4 |
+---+
"#
        .trim();
        assert_results_match_expected(plan, expected).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_single_local() -> Result<()> {
        let source = mock_data()?;
        let schema = source.schema();

        // `SELECT a FROM MemoryExec GROUP BY a LIMIT 4;`, Single AggregateExec
        let single_agg = AggregateExec::try_new(
            AggregateMode::Single,
            build_group_by(&schema.clone(), vec!["a".to_string()]),
            vec![],         /* aggr_expr */
            vec![],         /* filter_expr */
            source,         /* input */
            schema.clone(), /* input_schema */
        )?;
        let limit_exec = LocalLimitExec::new(
            Arc::new(single_agg),
            4, // fetch
        );
        // expected to push the limit to the AggregateExec
        let expected = [
            "LocalLimitExec: fetch=4",
            "AggregateExec: mode=Single, gby=[a@0 as a], aggr=[], lim=[4]",
            "MemoryExec: partitions=1, partition_sizes=[1]",
        ];
        let plan: Arc<dyn ExecutionPlan> = Arc::new(limit_exec);
        assert_plan_matches_expected(&plan, &expected)?;
        let expected = r#"
+---+
| a |
+---+
| 1 |
| 2 |
|   |
| 4 |
+---+
"#
        .trim();
        assert_results_match_expected(plan, expected).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_single_global() -> Result<()> {
        let source = mock_data()?;
        let schema = source.schema();

        // `SELECT a FROM MemoryExec GROUP BY a LIMIT 4;`, Single AggregateExec
        let single_agg = AggregateExec::try_new(
            AggregateMode::Single,
            build_group_by(&schema.clone(), vec!["a".to_string()]),
            vec![],         /* aggr_expr */
            vec![],         /* filter_expr */
            source,         /* input */
            schema.clone(), /* input_schema */
        )?;
        let limit_exec = GlobalLimitExec::new(
            Arc::new(single_agg),
            1,       // skip
            Some(3), // fetch
        );
        // expected to push the skip+fetch limit to the AggregateExec
        let expected = [
            "GlobalLimitExec: skip=1, fetch=3",
            "AggregateExec: mode=Single, gby=[a@0 as a], aggr=[], lim=[4]",
            "MemoryExec: partitions=1, partition_sizes=[1]",
        ];
        let plan: Arc<dyn ExecutionPlan> = Arc::new(limit_exec);
        assert_plan_matches_expected(&plan, &expected)?;
        let expected = r#"
+---+
| a |
+---+
| 2 |
|   |
| 4 |
+---+
"#
        .trim();
        assert_results_match_expected(plan, expected).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_distinct_cols_different_than_group_by_cols() -> Result<()> {
        let source = mock_data()?;
        let schema = source.schema();

        // `SELECT distinct a FROM MemoryExec GROUP BY a, b LIMIT 4;`, Single/Single AggregateExec
        let group_by_agg = AggregateExec::try_new(
            AggregateMode::Single,
            build_group_by(&schema.clone(), vec!["a".to_string(), "b".to_string()]),
            vec![],         /* aggr_expr */
            vec![],         /* filter_expr */
            source,         /* input */
            schema.clone(), /* input_schema */
        )?;
        let distinct_agg = AggregateExec::try_new(
            AggregateMode::Single,
            build_group_by(&schema.clone(), vec!["a".to_string()]),
            vec![],                 /* aggr_expr */
            vec![],                 /* filter_expr */
            Arc::new(group_by_agg), /* input */
            schema.clone(),         /* input_schema */
        )?;
        let limit_exec = LocalLimitExec::new(
            Arc::new(distinct_agg),
            4, // fetch
        );
        // expected to push the limit to the outer AggregateExec only
        let expected = [
            "LocalLimitExec: fetch=4",
            "AggregateExec: mode=Single, gby=[a@0 as a], aggr=[], lim=[4]",
            "AggregateExec: mode=Single, gby=[a@0 as a, b@1 as b], aggr=[]",
            "MemoryExec: partitions=1, partition_sizes=[1]",
        ];
        let plan: Arc<dyn ExecutionPlan> = Arc::new(limit_exec);
        assert_plan_matches_expected(&plan, &expected)?;
        let expected = r#"
+---+
| a |
+---+
| 1 |
| 2 |
|   |
| 4 |
+---+
"#
        .trim();
        assert_results_match_expected(plan, expected).await?;
        Ok(())
    }

    #[test]
    fn test_no_group_by() -> Result<()> {
        let source = mock_data()?;
        let schema = source.schema();

        // `SELECT <aggregate with no expressions> FROM MemoryExec LIMIT 10;`, Single AggregateExec
        let single_agg = AggregateExec::try_new(
            AggregateMode::Single,
            build_group_by(&schema.clone(), vec![]),
            vec![],         /* aggr_expr */
            vec![],         /* filter_expr */
            source,         /* input */
            schema.clone(), /* input_schema */
        )?;
        let limit_exec = LocalLimitExec::new(
            Arc::new(single_agg),
            10, // fetch
        );
        // expected not to push the limit to the AggregateExec
        let expected = [
            "LocalLimitExec: fetch=10",
            "AggregateExec: mode=Single, gby=[], aggr=[]",
            "MemoryExec: partitions=1, partition_sizes=[1]",
        ];
        let plan: Arc<dyn ExecutionPlan> = Arc::new(limit_exec);
        assert_plan_matches_expected(&plan, &expected)?;
        Ok(())
    }

    #[test]
    fn test_has_aggregate_expression() -> Result<()> {
        let source = mock_data()?;
        let schema = source.schema();
        let agg = TestAggregate::new_count_star();

        // `SELECT <aggregate with no expressions> FROM MemoryExec LIMIT 10;`, Single AggregateExec
        let single_agg = AggregateExec::try_new(
            AggregateMode::Single,
            build_group_by(&schema.clone(), vec!["a".to_string()]),
            vec![agg.count_expr(&schema)], /* aggr_expr */
            vec![None],                    /* filter_expr */
            source,                        /* input */
            schema.clone(),                /* input_schema */
        )?;
        let limit_exec = LocalLimitExec::new(
            Arc::new(single_agg),
            10, // fetch
        );
        // expected not to push the limit to the AggregateExec
        let expected = [
            "LocalLimitExec: fetch=10",
            "AggregateExec: mode=Single, gby=[a@0 as a], aggr=[COUNT(*)]",
            "MemoryExec: partitions=1, partition_sizes=[1]",
        ];
        let plan: Arc<dyn ExecutionPlan> = Arc::new(limit_exec);
        assert_plan_matches_expected(&plan, &expected)?;
        Ok(())
    }

    #[test]
    fn test_has_filter() -> Result<()> {
        let source = mock_data()?;
        let schema = source.schema();

        // `SELECT a FROM MemoryExec WHERE a > 1 GROUP BY a LIMIT 10;`, Single AggregateExec
        // the `a > 1` filter is applied in the AggregateExec
        let filter_expr = Some(expressions::binary(
            expressions::col("a", &schema)?,
            Operator::Gt,
            cast(expressions::lit(1u32), &schema, DataType::Int32)?,
            &schema,
        )?);
        let agg = TestAggregate::new_count_star();
        let single_agg = AggregateExec::try_new(
            AggregateMode::Single,
            build_group_by(&schema.clone(), vec!["a".to_string()]),
            vec![agg.count_expr(&schema)], /* aggr_expr */
            vec![filter_expr],             /* filter_expr */
            source,                        /* input */
            schema.clone(),                /* input_schema */
        )?;
        let limit_exec = LocalLimitExec::new(
            Arc::new(single_agg),
            10, // fetch
        );
        // expected not to push the limit to the AggregateExec
        // TODO(msirek): open an issue for `filter_expr` of `AggregateExec` not printing out
        let expected = [
            "LocalLimitExec: fetch=10",
            "AggregateExec: mode=Single, gby=[a@0 as a], aggr=[COUNT(*)]",
            "MemoryExec: partitions=1, partition_sizes=[1]",
        ];
        let plan: Arc<dyn ExecutionPlan> = Arc::new(limit_exec);
        assert_plan_matches_expected(&plan, &expected)?;
        Ok(())
    }

    #[test]
    fn test_has_order_by() -> Result<()> {
        let sort_key = vec![PhysicalSortExpr {
            expr: expressions::col("a", &schema()).unwrap(),
            options: SortOptions::default(),
        }];
        let source = parquet_exec_with_sort(vec![sort_key]);
        let schema = source.schema();

        // `SELECT a FROM MemoryExec WHERE a > 1 GROUP BY a LIMIT 10;`, Single AggregateExec
        // the `a > 1` filter is applied in the AggregateExec
        let single_agg = AggregateExec::try_new(
            AggregateMode::Single,
            build_group_by(&schema.clone(), vec!["a".to_string()]),
            vec![],         /* aggr_expr */
            vec![],         /* filter_expr */
            source,         /* input */
            schema.clone(), /* input_schema */
        )?;
        let limit_exec = LocalLimitExec::new(
            Arc::new(single_agg),
            10, // fetch
        );
        // expected not to push the limit to the AggregateExec
        let expected = [
            "LocalLimitExec: fetch=10",
            "AggregateExec: mode=Single, gby=[a@0 as a], aggr=[], ordering_mode=Sorted",
            "ParquetExec: file_groups={1 group: [[x]]}, projection=[a, b, c, d, e], output_ordering=[a@0 ASC]",
        ];
        let plan: Arc<dyn ExecutionPlan> = Arc::new(limit_exec);
        assert_plan_matches_expected(&plan, &expected)?;
        Ok(())
    }
}