datafusion 56.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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

mod data_utils;

use arrow::array::{Array, AsArray};
use arrow::datatypes::{
    DataType, Int32Type, Int64Type, IntervalUnit, TimeUnit, TimestampNanosecondType,
};
use criterion::{Criterion, criterion_group, criterion_main};
use data_utils::create_table_provider;
use datafusion::datasource::MemTable;
use datafusion::error::Result;
use datafusion::execution::context::{SessionConfig, SessionContext};
use datafusion::physical_plan::{collect, displayable};
use datafusion_expr::col;
use parking_lot::Mutex;
use std::hint::black_box;
use std::sync::Arc;
use tokio::runtime::Runtime;

#[expect(clippy::needless_pass_by_value)]
fn query(ctx: Arc<Mutex<SessionContext>>, rt: &Runtime, sql: &str) {
    let df = rt.block_on(ctx.lock().sql(sql)).unwrap();
    black_box(rt.block_on(df.collect()).unwrap());
}

fn create_context(
    partitions_len: usize,
    array_len: usize,
    batch_size: usize,
) -> Result<Arc<Mutex<SessionContext>>> {
    let ctx = SessionContext::new();
    let provider = create_table_provider(partitions_len, array_len, batch_size)?;
    ctx.register_table("t", provider)?;
    Ok(Arc::new(Mutex::new(ctx)))
}

fn criterion_benchmark(c: &mut Criterion) {
    let partitions_len = 8;
    let array_len = 32768 * 2; // 2^16
    let batch_size = 2048; // 2^11
    let ctx = create_context(partitions_len, array_len, batch_size).unwrap();
    let rt = Runtime::new().unwrap();

    c.bench_function("aggregate_query_no_group_by 15 12", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT MIN(f64), AVG(f64), COUNT(f64) \
                 FROM t",
            )
        })
    });

    c.bench_function("aggregate_query_no_group_by_min_max_f64", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT MIN(f64), MAX(f64) \
                 FROM t",
            )
        })
    });

    c.bench_function("aggregate_query_no_group_by_count_distinct_wide", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT COUNT(DISTINCT u64_wide) \
                 FROM t",
            )
        })
    });

    c.bench_function("aggregate_query_no_group_by_count_distinct_narrow", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT COUNT(DISTINCT u64_narrow) \
                 FROM t",
            )
        })
    });

    c.bench_function("aggregate_query_group_by", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT utf8, MIN(f64), AVG(f64), COUNT(f64) \
                 FROM t GROUP BY utf8",
            )
        })
    });

    c.bench_function("aggregate_query_group_by_with_filter", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT utf8, MIN(f64), AVG(f64), COUNT(f64) \
                 FROM t \
                 WHERE f32 > 10 AND f32 < 20 GROUP BY utf8",
            )
        })
    });

    c.bench_function("aggregate_query_group_by_u64 15 12", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT u64_narrow, MIN(f64), AVG(f64), COUNT(f64) \
                 FROM t GROUP BY u64_narrow",
            )
        })
    });

    c.bench_function("aggregate_query_group_by_with_filter_u64 15 12", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT u64_narrow, MIN(f64), AVG(f64), COUNT(f64) \
                 FROM t \
                 WHERE f32 > 10 AND f32 < 20 GROUP BY u64_narrow",
            )
        })
    });

    c.bench_function("aggregate_query_group_by_u64_multiple_keys", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT u64_wide, utf8, MIN(f64), AVG(f64), COUNT(f64) \
                 FROM t GROUP BY u64_wide, utf8",
            )
        })
    });

    c.bench_function(
        "aggregate_query_group_by_wide_u64_and_string_without_aggregate_expressions",
        |b| {
            b.iter(|| {
                query(
                    ctx.clone(),
                    &rt,
                    // Due to the large number of distinct values in u64_wide,
                    // this query test the actual grouping performance for more than 1 column
                    "SELECT u64_wide, utf8 \
                 FROM t GROUP BY u64_wide, utf8",
                )
            })
        },
    );

    c.bench_function(
        "aggregate_query_group_by_wide_u64_and_f32_without_aggregate_expressions",
        |b| {
            b.iter(|| {
                query(
                    ctx.clone(),
                    &rt,
                    // Due to the large number of distinct values in u64_wide,
                    // this query test the actual grouping performance for more than 1 column
                    "SELECT u64_wide, f32 \
                 FROM t GROUP BY u64_wide, f32",
                )
            })
        },
    );

    c.bench_function("aggregate_query_approx_percentile_cont_on_u64", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT utf8, approx_percentile_cont(0.5, 2500) WITHIN GROUP (ORDER BY u64_wide)  \
                 FROM t GROUP BY utf8",
            )
        })
    });

    c.bench_function("aggregate_query_approx_percentile_cont_on_f32", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT utf8, approx_percentile_cont(0.5, 2500) WITHIN GROUP (ORDER BY f32)  \
                 FROM t GROUP BY utf8",
            )
        })
    });

    c.bench_function("aggregate_query_distinct_median", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT MEDIAN(DISTINCT u64_wide), MEDIAN(DISTINCT u64_narrow) \
                 FROM t",
            )
        })
    });

    c.bench_function("first_last_many_columns", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT first_value(u64_wide order by f64, u64_narrow, utf8),\
                            last_value(u64_wide order by f64, u64_narrow, utf8)  \
                 FROM t GROUP BY u64_narrow",
            )
        })
    });

    c.bench_function("first_last_ignore_nulls", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT first_value(u64_wide ignore nulls order by f64, u64_narrow, utf8),  \
                            last_value(u64_wide ignore nulls order by f64, u64_narrow, utf8)    \
                 FROM t GROUP BY u64_narrow",
            )
        })
    });

    c.bench_function("first_last_one_column", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT first_value(u64_wide order by f64), \
                            last_value(u64_wide order by f64)   \
                FROM t GROUP BY u64_narrow",
            )
        })
    });

    c.bench_function("array_agg_query_group_by_few_groups", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT u64_narrow, array_agg(f64) \
                 FROM t GROUP BY u64_narrow",
            )
        })
    });

    c.bench_function("array_agg_query_group_by_mid_groups", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT u64_mid, array_agg(f64) \
                 FROM t GROUP BY u64_mid",
            )
        })
    });

    c.bench_function("array_agg_query_group_by_many_groups", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT u64_wide, array_agg(f64) \
                 FROM t GROUP BY u64_wide",
            )
        })
    });

    c.bench_function("array_agg_struct_query_group_by_mid_groups", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT u64_mid, array_agg(named_struct('market', dict10, 'price', f64)) \
                 FROM t GROUP BY u64_mid",
            )
        })
    });

    c.bench_function("string_agg_query_group_by_few_groups", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT u64_narrow, string_agg(utf8, ',') \
                 FROM t GROUP BY u64_narrow",
            )
        })
    });

    c.bench_function("string_agg_query_group_by_mid_groups", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT u64_mid, string_agg(utf8, ',') \
                 FROM t GROUP BY u64_mid",
            )
        })
    });

    c.bench_function("string_agg_query_group_by_many_groups", |b| {
        b.iter(|| {
            query(
                ctx.clone(),
                &rt,
                "SELECT u64_wide, string_agg(utf8, ',') \
                 FROM t GROUP BY u64_wide",
            )
        })
    });
}

/// Measure the multi-column fully ordered grouping path, with data generation
/// and sorting outside timing. Both keys vary, and the nullable second key
/// changes type while the shape of the input stays the same.
fn fully_ordered(c: &mut Criterion) {
    use DataType::*;
    use IntervalUnit::{DayTime, MonthDayNano};
    use TimeUnit::{Microsecond, Millisecond, Nanosecond};

    let cases = [
        ("int64", "signed_key", Int64, 31),
        (
            "utf8_view",
            "arrow_cast(lpad(CAST(key_value AS VARCHAR), 4, '0'), 'Utf8View')",
            Utf8View,
            31,
        ),
        (
            "timestamp_ns",
            "arrow_cast(signed_key, 'Timestamp(Nanosecond)')",
            Timestamp(Nanosecond, None),
            31,
        ),
        (
            "timestamp_us_utc",
            "arrow_cast(signed_key, 'Timestamp(Microsecond, Some(\"UTC\"))')",
            Timestamp(Microsecond, Some("UTC".into())),
            31,
        ),
        (
            "date32",
            "arrow_cast(CAST(signed_key AS INTEGER), 'Date32')",
            Date32,
            31,
        ),
        (
            "time32_ms",
            "arrow_cast(CAST(key_value AS INTEGER), 'Time32(Millisecond)')",
            Time32(Millisecond),
            31,
        ),
        (
            "time64_ns",
            "arrow_cast(key_value, 'Time64(Nanosecond)')",
            Time64(Nanosecond),
            31,
        ),
        (
            "duration_ns",
            "arrow_cast(signed_key, 'Duration(Nanosecond)')",
            Duration(Nanosecond),
            31,
        ),
        (
            "interval_day_time",
            "arrow_cast(concat(CAST(signed_key AS VARCHAR), ' days'), 'Interval(DayTime)')",
            Interval(DayTime),
            31,
        ),
        (
            "interval_month_day_nano",
            "arrow_cast(arrow_cast(signed_key, 'Duration(Nanosecond)'), 'Interval(MonthDayNano)')",
            Interval(MonthDayNano),
            31,
        ),
        (
            "decimal128",
            "arrow_cast(concat('123456789012345678901', lpad(CAST(key_value AS VARCHAR), 4, '0'), '.1250'), 'Decimal128(30, 4)')",
            Decimal128(30, 4),
            31,
        ),
        (
            "decimal256",
            "arrow_cast(concat('123456789012345678901234567890123456789012345678901', lpad(CAST(key_value AS VARCHAR), 4, '0'), '.1250'), 'Decimal256(60, 4)')",
            Decimal256(60, 4),
            31,
        ),
        (
            "fixed_binary16",
            "arrow_cast(decode(lpad(to_hex(key_value), 32, '0'), 'hex'), 'FixedSizeBinary(16)')",
            FixedSizeBinary(16),
            31,
        ),
        (
            "fixed_binary7",
            "arrow_cast(decode(lpad(to_hex(key_value), 14, '0'), 'hex'), 'FixedSizeBinary(7)')",
            FixedSizeBinary(7),
            31,
        ),
        (
            "timestamp_ns_singleton",
            "arrow_cast(signed_key, 'Timestamp(Nanosecond)')",
            Timestamp(Nanosecond, None),
            1,
        ),
        (
            "timestamp_ns_long_runs",
            "arrow_cast(signed_key, 'Timestamp(Nanosecond)')",
            Timestamp(Nanosecond, None),
            512,
        ),
    ];

    let rt = Runtime::new().unwrap();
    let mut group = c.benchmark_group("fully_ordered");
    for (name, key_expr, key_type, run_length) in cases {
        let ctx = rt
            .block_on(fully_ordered_context(
                key_expr, &key_type, run_length, false,
            ))
            .unwrap();
        group.bench_function(name, |b| {
            b.iter(|| query(ctx.clone(), &rt, FULLY_ORDERED_QUERY))
        });
    }
    // Add accumulator work for one representative timestamp case without
    // multiplying every key type and run length by the aggregate expression.
    let ctx = rt
        .block_on(fully_ordered_context(
            "arrow_cast(signed_key, 'Timestamp(Nanosecond)')",
            &Timestamp(Nanosecond, None),
            31,
            true,
        ))
        .unwrap();
    group.bench_function("timestamp_ns_sum", |b| {
        b.iter(|| query(ctx.clone(), &rt, FULLY_ORDERED_SUM_QUERY))
    });
    group.finish();
}

const FULLY_ORDERED_QUERY: &str = "SELECT k1, k2 FROM ordered_input GROUP BY k1, k2";
const FULLY_ORDERED_SUM_QUERY: &str =
    "SELECT k1, k2, SUM(v) FROM ordered_input GROUP BY k1, k2";

async fn fully_ordered_context(
    key_expr: &str,
    key_type: &DataType,
    run_length: usize,
    with_sum: bool,
) -> Result<Arc<Mutex<SessionContext>>> {
    const ROWS: usize = 2_097_152;
    // Use source row numbers as nonconstant values for the aggregate case.
    let (value_projection, input_value, sql) = if with_sum {
        (", v", ", value AS v", FULLY_ORDERED_SUM_QUERY)
    } else {
        ("", "", FULLY_ORDERED_QUERY)
    };
    let config = SessionConfig::new()
        .with_target_partitions(1)
        .with_batch_size(8192)
        .with_prefer_existing_sort(true);
    let ctx = SessionContext::new_with_config(config);
    // Runs of 31 cross batch boundaries; singleton and long-run cases vary
    // cardinality without multiplying every type by every input shape.
    let input = ctx
        .sql(&format!(
            "SELECT CAST(group_id / 32 AS INTEGER) AS k1, \
             CASE WHEN key_value = 0 THEN NULL ELSE {key_expr} END AS k2{value_projection} \
             FROM (SELECT value / {run_length} AS group_id, \
                          value / {run_length} % 32 AS key_value, \
                          value / {run_length} % 32 - 16 AS signed_key{input_value} \
                   FROM range({ROWS})) \
             ORDER BY k1 ASC NULLS FIRST, k2 ASC NULLS FIRST"
        ))
        .await?
        .create_physical_plan()
        .await?;
    let schema = input.schema();
    assert_eq!(schema.field(1).data_type(), key_type);
    let batches = collect(input, ctx.task_ctx()).await?;
    assert_eq!(
        batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
        ROWS
    );
    // The setup query sorts both keys before materialization. Retain that
    // known ordering explicitly when registering its results as a table.
    let table = MemTable::try_new(schema, vec![batches])?.with_sort_order(vec![vec![
        col("k1").sort(true, true),
        col("k2").sort(true, true),
    ]]);
    ctx.register_table("ordered_input", Arc::new(table))?;

    let plan = ctx.sql(sql).await?.create_physical_plan().await?;
    let description = displayable(plan.as_ref()).indent(true).to_string();
    assert!(
        description.contains("group_clustering_mode=Full"),
        "{description}"
    );
    // Input is already sorted in one partition. Fail if the planner adds
    // sorting or repartitioning to the measured query.
    assert!(!description.contains("SortExec"), "{description}");
    assert!(!description.contains("RepartitionExec"), "{description}");
    let result = collect(plan, ctx.task_ctx()).await?;
    assert_eq!(
        result.iter().map(|batch| batch.num_rows()).sum::<usize>(),
        ROWS.div_ceil(run_length)
    );
    if with_sum {
        let rows = i64::try_from(ROWS).unwrap();
        let run_length = i64::try_from(run_length).unwrap();
        for batch in &result {
            let k1 = batch.column(0).as_primitive::<Int32Type>();
            let k2 = batch.column(1).as_primitive::<TimestampNanosecondType>();
            let sums = batch.column(2).as_primitive::<Int64Type>();
            assert_eq!(sums.null_count(), 0);
            for row in 0..batch.num_rows() {
                // Each input group covers a contiguous range of source row
                // numbers. Recover it from the keys, independently of output
                // order, and check the arithmetic-series sum, including the
                // final short group and groups with a NULL timestamp key.
                let key_offset = if k2.is_null(row) {
                    0
                } else {
                    k2.value(row) + 16
                };
                let group_id = i64::from(k1.value(row)) * 32 + key_offset;
                let start = group_id * run_length;
                let end = (start + run_length).min(rows);
                assert_eq!(sums.value(row), (start + end - 1) * (end - start) / 2);
            }
        }
    }
    Ok(Arc::new(Mutex::new(ctx)))
}

criterion_group!(benches, criterion_benchmark, fully_ordered);
criterion_main!(benches);