datafusion-physical-expr 56.0.0

Physical expression implementation for DataFusion query engine
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
// 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

use arrow::array::{ArrayRef, Int32Array, Int64Array};
use arrow::{array::StringArray, record_batch::RecordBatch};
use arrow::{
    array::{BooleanArray, Date32Array, Date64Array},
    datatypes::{DataType, Field, Schema},
};
use criterion::{Criterion, criterion_group, criterion_main};
use datafusion_common::ScalarValue;
use datafusion_expr::{Operator, and, binary_expr, col, lit, or};
use datafusion_physical_expr::{
    PhysicalExpr,
    expressions::{BinaryExpr, Column, Literal, cast, in_list},
    planner::logical2physical,
};
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use std::hint::black_box;
use std::sync::Arc;

const DATE_ARRAY_LEN: usize = 8192;
const MILLIS_PER_DAY: i64 = 86_400_000;

/// Generates BooleanArrays with different true/false distributions for benchmarking.
///
/// Returns a vector of tuples containing scenario name and corresponding BooleanArray.
///
/// # Arguments
/// - `TEST_ALL_FALSE` - Used to generate what kind of test data
/// - `len` - Length of the BooleanArray to generate
fn generate_boolean_cases<const TEST_ALL_FALSE: bool>(
    len: usize,
) -> Vec<(String, BooleanArray)> {
    let mut cases = Vec::with_capacity(6);

    // Scenario 1: All elements false or all elements true
    if TEST_ALL_FALSE {
        let all_false = BooleanArray::from(vec![false; len]);
        cases.push(("all_false".to_string(), all_false));
    } else {
        let all_true = BooleanArray::from(vec![true; len]);
        cases.push(("all_true".to_string(), all_true));
    }

    // Scenario 2: Single true at first position or single false at first position
    if TEST_ALL_FALSE {
        let mut first_true = vec![false; len];
        first_true[0] = true;
        cases.push(("one_true_first".to_string(), BooleanArray::from(first_true)));
    } else {
        let mut first_false = vec![true; len];
        first_false[0] = false;
        cases.push((
            "one_false_first".to_string(),
            BooleanArray::from(first_false),
        ));
    }

    // Scenario 3: Single true at last position or single false at last position
    if TEST_ALL_FALSE {
        let mut last_true = vec![false; len];
        last_true[len - 1] = true;
        cases.push(("one_true_last".to_string(), BooleanArray::from(last_true)));
    } else {
        let mut last_false = vec![true; len];
        last_false[len - 1] = false;
        cases.push(("one_false_last".to_string(), BooleanArray::from(last_false)));
    }

    // Scenario 4: Single true at exact middle or single false at exact middle
    let mid = len / 2;
    if TEST_ALL_FALSE {
        let mut mid_true = vec![false; len];
        mid_true[mid] = true;
        cases.push(("one_true_middle".to_string(), BooleanArray::from(mid_true)));
    } else {
        let mut mid_false = vec![true; len];
        mid_false[mid] = false;
        cases.push((
            "one_false_middle".to_string(),
            BooleanArray::from(mid_false),
        ));
    }

    // Scenario 5: Single true at 25% position or single false at 25% position
    let mid_left = len / 4;
    if TEST_ALL_FALSE {
        let mut mid_left_true = vec![false; len];
        mid_left_true[mid_left] = true;
        cases.push((
            "one_true_middle_left".to_string(),
            BooleanArray::from(mid_left_true),
        ));
    } else {
        let mut mid_left_false = vec![true; len];
        mid_left_false[mid_left] = false;
        cases.push((
            "one_false_middle_left".to_string(),
            BooleanArray::from(mid_left_false),
        ));
    }

    // Scenario 6: Single true at 75% position or single false at 75% position
    let mid_right = (3 * len) / 4;
    if TEST_ALL_FALSE {
        let mut mid_right_true = vec![false; len];
        mid_right_true[mid_right] = true;
        cases.push((
            "one_true_middle_right".to_string(),
            BooleanArray::from(mid_right_true),
        ));
    } else {
        let mut mid_right_false = vec![true; len];
        mid_right_false[mid_right] = false;
        cases.push((
            "one_false_middle_right".to_string(),
            BooleanArray::from(mid_right_false),
        ));
    }

    // Scenario 7: Test all true or all false in AND/OR
    // This situation won't cause a short circuit, but it can skip the bool calculation
    if TEST_ALL_FALSE {
        let all_true = vec![true; len];
        cases.push(("all_true_in_and".to_string(), BooleanArray::from(all_true)));
    } else {
        let all_false = vec![false; len];
        cases.push(("all_false_in_or".to_string(), BooleanArray::from(all_false)));
    }

    cases
}

/// Benchmarks AND/OR operator short-circuiting by evaluating complex regex conditions.
///
/// Creates 7 test scenarios per operator:
/// 1. All values enable short-circuit (all_true/all_false)
/// 2. 2-6 Single true/false value at different positions to measure early exit
/// 3. Test all true or all false in AND/OR
///
/// You can run this benchmark with:
/// ```sh
/// cargo bench --bench binary_op -- short_circuit
/// ```
fn benchmark_binary_op_in_short_circuit(c: &mut Criterion) {
    // Create schema with three columns
    let schema = Arc::new(Schema::new(vec![
        Field::new("a", DataType::Boolean, false),
        Field::new("b", DataType::Utf8, false),
        Field::new("c", DataType::Utf8, false),
    ]));

    // Generate test data with extended content
    let (b_values, c_values) = generate_test_strings(8192);

    let batches_and =
        create_record_batch::<true>(schema.clone(), &b_values, &c_values).unwrap();
    let batches_or =
        create_record_batch::<false>(schema.clone(), &b_values, &c_values).unwrap();

    // Build complex string matching conditions
    let right_condition_and = and(
        // Check for API endpoint pattern in URLs
        binary_expr(
            col("b"),
            Operator::RegexMatch,
            lit(r#"^https://(\w+\.)?example\.(com|org)/"#),
        ),
        // Check for markdown code blocks and summary section
        binary_expr(
            col("c"),
            Operator::RegexMatch,
            lit("```(rust|python|go)\nfn? main$$"),
        ),
    );

    let right_condition_or = or(
        // Check for secure HTTPS protocol
        binary_expr(
            col("b"),
            Operator::RegexMatch,
            lit(r#"^https://(\w+\.)?example\.(com|org)/"#),
        ),
        // Check for Rust code examples
        binary_expr(
            col("c"),
            Operator::RegexMatch,
            lit("```(rust|python|go)\nfn? main$$"),
        ),
    );

    // Create physical binary expressions
    // a AND ((b ~ regex) AND (c ~ regex))
    let expr_and = BinaryExpr::new(
        Arc::new(Column::new("a", 0)),
        Operator::And,
        logical2physical(&right_condition_and, &schema),
    );

    // a OR ((b ~ regex) OR (c ~ regex))
    let expr_or = BinaryExpr::new(
        Arc::new(Column::new("a", 0)),
        Operator::Or,
        logical2physical(&right_condition_or, &schema),
    );

    // Each scenario when the test operator is `and`
    {
        for (name, batch) in batches_and.into_iter() {
            c.bench_function(&format!("short_circuit/and/{name}"), |b| {
                b.iter(|| expr_and.evaluate(black_box(&batch)).unwrap())
            });
        }
    }
    // Each scenario when the test operator is `or`
    {
        for (name, batch) in batches_or.into_iter() {
            c.bench_function(&format!("short_circuit/or/{name}"), |b| {
                b.iter(|| expr_or.evaluate(black_box(&batch)).unwrap())
            });
        }
    }
}

/// How each conjunct in [`benchmark_conjunction`] tests its column.
#[derive(Clone, Copy, PartialEq)]
enum ConjunctKind {
    /// `c < x`
    Lt,
    /// `CAST(c AS BIGINT) < x`
    CastLt,
    /// `c IN (...)`
    InList,
    /// `c + 1 < x`
    Plus,
}

/// Benchmarks left- and right-deep `AND` chains across selectivity, expression
/// types, NULLs, and unused columns (#25035).
///
/// Run with `cargo bench --bench binary_op -- conjunction`.
fn benchmark_conjunction(c: &mut Criterion) {
    use ConjunctKind::*;
    const NUM_ROWS: usize = 8192;
    let mut rng = StdRng::seed_from_u64(25035);
    let urls = generate_test_strings(NUM_ROWS).0;

    // (per-conjunct pass rates, label, kind, null rate, regex suffix)
    for (pass_rates, pass_rate_label, kind, null_rate, regex) in [
        (&[0.5; 4] as &[f64], "0.5", Lt, 0.0, false),
        (&[0.7; 8], "0.7", Lt, 0.0, false),
        (&[0.9; 8], "0.9", Lt, 0.0, false),
        (&[0.7; 16], "0.7", Lt, 0.0, false),
        (&[0.7; 8], "0.7", Lt, 0.0, true),
        (&[0.7; 8], "0.7", CastLt, 0.0, false),
        (&[0.7; 8], "0.7", InList, 0.0, false),
        // Nulls disable pre-selection (check_short_circuit returns None when the
        // LHS has nulls), so both shapes should match; baseline for an n-ary fix.
        (&[0.5; 4], "0.5", Lt, 0.1, true),
        (&[0.7; 8], "0.7", Plus, 0.0, false),
        // Selective c0 enables pre-selection in both shapes. Cover cheap and
        // expensive remaining work to catch regressions where it helps today.
        (
            &[0.1, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9],
            "0.1_then0.9",
            Lt,
            0.0,
            false,
        ),
        (
            &[0.1, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9],
            "0.1_then0.9",
            Lt,
            0.0,
            true,
        ),
    ] {
        let num_conjuncts = pass_rates.len();
        // `InList` draws values from 0..10, the others from 0..1000.
        let domain = if kind == InList { 10 } else { 1000 };
        let conjunct_schema = Schema::new(
            (0..num_conjuncts)
                .map(|i| Field::new(format!("c{i}"), DataType::Int32, null_rate > 0.0))
                .collect::<Vec<_>>(),
        );
        let mut conjuncts: Vec<Arc<dyn PhysicalExpr>> = pass_rates
            .iter()
            .enumerate()
            .map(|(i, pass_rate)| {
                let cutoff = (pass_rate * domain as f64) as i32;
                let column = Arc::new(Column::new(&format!("c{i}"), i)) as _;
                match kind {
                    Lt => Arc::new(BinaryExpr::new(
                        column,
                        Operator::Lt,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(cutoff)))),
                    )) as _,
                    CastLt => Arc::new(BinaryExpr::new(
                        cast(column, &conjunct_schema, DataType::Int64).unwrap(),
                        Operator::Lt,
                        Arc::new(Literal::new(ScalarValue::Int64(Some(cutoff as i64)))),
                    )),
                    Plus => Arc::new(BinaryExpr::new(
                        Arc::new(BinaryExpr::new(
                            column,
                            Operator::Plus,
                            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
                        )),
                        Operator::Lt,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(cutoff + 1)))),
                    )),
                    InList => in_list(
                        column,
                        (0..cutoff)
                            .map(|v| {
                                Arc::new(Literal::new(ScalarValue::Int32(Some(v)))) as _
                            })
                            .collect(),
                        &false,
                        &conjunct_schema,
                    )
                    .unwrap(),
                }
            })
            .collect();
        if regex {
            conjuncts.push(Arc::new(BinaryExpr::new(
                Arc::new(Column::new("url", num_conjuncts)),
                Operator::RegexMatch,
                Arc::new(Literal::new(ScalarValue::from(
                    r#"^https://(\w+\.)?example\.(com|org)/"#,
                ))),
            )));
        }
        let left_deep = conjuncts
            .iter()
            .cloned()
            .reduce(|l, r| Arc::new(BinaryExpr::new(l, Operator::And, r)))
            .unwrap();
        let right_deep = conjuncts
            .iter()
            .cloned()
            .rev()
            .reduce(|r, l| Arc::new(BinaryExpr::new(l, Operator::And, r)))
            .unwrap();

        let conjunct_columns: Vec<ArrayRef> = (0..num_conjuncts)
            .map(|_| {
                Arc::new(if null_rate > 0.0 {
                    Int32Array::from_iter((0..NUM_ROWS).map(|_| {
                        let value = rng.random_range(0..domain);
                        (!rng.random_bool(null_rate)).then_some(value)
                    }))
                } else {
                    Int32Array::from_iter_values(
                        (0..NUM_ROWS).map(|_| rng.random_range(0..domain)),
                    )
                }) as ArrayRef
            })
            .collect();

        for payload_columns in [0, 32] {
            let mut fields = conjunct_schema.fields().to_vec();
            let mut columns = conjunct_columns.clone();
            if regex {
                fields.push(Arc::new(Field::new("url", DataType::Utf8, false)));
                columns.push(Arc::new(StringArray::from(urls.clone())));
            }
            for i in 0..payload_columns {
                fields.push(Arc::new(Field::new(
                    format!("p{i}"),
                    DataType::Int64,
                    false,
                )));
                columns.push(Arc::new(Int64Array::from_iter_values(
                    (0..NUM_ROWS).map(|_| rng.random()),
                )));
            }
            let batch =
                RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap();

            let suffix = [
                (kind == CastLt, "_cast"),
                (kind == InList, "_inlist"),
                (kind == Plus, "_plus"),
                (null_rate > 0.0, "_nulls"),
                (regex, "_regex"),
            ]
            .into_iter()
            .filter_map(|(on, tag)| on.then_some(tag))
            .collect::<String>();
            for (shape, expr) in [("left_deep", &left_deep), ("right_deep", &right_deep)]
            {
                c.bench_function(
                    &format!(
                        "conjunction/k{num_conjuncts}_p{pass_rate_label}{suffix}_w{payload_columns}/{shape}"
                    ),
                    |b| b.iter(|| expr.evaluate(black_box(&batch)).unwrap()),
                );
            }
        }
    }
}

/// Generate test data with computationally expensive patterns
fn generate_test_strings(num_rows: usize) -> (Vec<String>, Vec<String>) {
    // Extended URL patterns with query parameters and paths
    let base_urls = [
        "https://api.example.com/v2/users/12345/posts?category=tech&sort=date&lang=en-US",
        "https://cdn.example.net/assets/images/2023/08/15/sample-image-highres.jpg?width=1920&quality=85",
        "http://service.demo.org:8080/api/data/transactions/20230815123456.csv",
        "ftp://legacy.archive.example/backups/2023/Q3/database-dump.sql.gz",
        "https://docs.example.co.uk/reference/advanced-topics/concurrency/parallel-processing.md#implementation-details",
    ];

    // Extended markdown content with code blocks and structure
    let base_markdowns = [
        concat!(
            "# Advanced Topics in Computer Science\n\n",
            "## Summary\nThis article explores complex system design patterns and...\n\n",
            "```rust\nfn process_data(data: &mut [i32]) {\n    // Parallel processing example\n    data.par_iter_mut().for_each(|x| *x *= 2);\n}\n```\n\n",
            "## Performance Considerations\nWhen implementing concurrent systems...\n"
        ),
        concat!(
            "## API Documentation\n\n",
            "```json\n{\n  \"endpoint\": \"/api/v2/users\",\n  \"methods\": [\"GET\", \"POST\"],\n  \"parameters\": {\n    \"page\": \"number\"\n  }\n}\n```\n\n",
            "# Authentication Guide\nSecure your API access using OAuth 2.0...\n"
        ),
        concat!(
            "# Data Processing Pipeline\n\n",
            "```python\nfrom multiprocessing import Pool\n\ndef main():\n    with Pool(8) as p:\n        results = p.map(process_item, data)\n```\n\n",
            "## Summary of Optimizations\n1. Batch processing\n2. Memory pooling\n3. Concurrent I/O operations\n"
        ),
        concat!(
            "# System Architecture Overview\n\n",
            "## Components\n- Load Balancer\n- Database Cluster\n- Cache Service\n\n",
            "```go\nfunc main() {\n    router := gin.Default()\n    router.GET(\"/api/health\", healthCheck)\n    router.Run(\":8080\")\n}\n```\n"
        ),
        concat!(
            "## Configuration Reference\n\n",
            "```yaml\nserver:\n  port: 8080\n  max_threads: 32\n\ndatabase:\n  url: postgres://user@prod-db:5432/main\n```\n\n",
            "# Deployment Strategies\nBlue-green deployment patterns with...\n"
        ),
    ];

    let mut urls = Vec::with_capacity(num_rows);
    let mut markdowns = Vec::with_capacity(num_rows);

    for i in 0..num_rows {
        urls.push(base_urls[i % 5].to_string());
        markdowns.push(base_markdowns[i % 5].to_string());
    }

    (urls, markdowns)
}

/// Creates record batches with boolean arrays that test different short-circuit scenarios.
/// When TEST_ALL_FALSE = true: creates data for AND operator benchmarks (needs early false exit)
/// When TEST_ALL_FALSE = false: creates data for OR operator benchmarks (needs early true exit)
#[expect(clippy::needless_pass_by_value)]
fn create_record_batch<const TEST_ALL_FALSE: bool>(
    schema: Arc<Schema>,
    b_values: &[String],
    c_values: &[String],
) -> arrow::error::Result<Vec<(String, RecordBatch)>> {
    // Generate data for six scenarios, but only the data for the "all_false" and "all_true" cases can be optimized through short-circuiting
    let boolean_array = generate_boolean_cases::<TEST_ALL_FALSE>(b_values.len());
    let mut rbs = Vec::with_capacity(boolean_array.len());
    for (name, a_array) in boolean_array {
        let b_array = StringArray::from(b_values.to_vec());
        let c_array = StringArray::from(c_values.to_vec());
        rbs.push((
            name,
            RecordBatch::try_new(
                schema.clone(),
                vec![Arc::new(a_array), Arc::new(b_array), Arc::new(c_array)],
            )?,
        ));
    }
    Ok(rbs)
}

fn make_date32_batch(null_percent: f64) -> RecordBatch {
    let schema = Arc::new(Schema::new(vec![
        Field::new("a", DataType::Date32, true),
        Field::new("b", DataType::Date32, true),
    ]));

    let left = Date32Array::from_iter((0..DATE_ARRAY_LEN).map(|i| {
        (null_percent == 0.0 || i % (1.0 / null_percent) as usize != 0)
            .then_some(18_000 + i as i32)
    }));
    let right = Date32Array::from_iter((0..DATE_ARRAY_LEN).map(|i| {
        (null_percent == 0.0 || i % (1.0 / null_percent) as usize != 0)
            .then_some(17_000 + (i % 365) as i32)
    }));

    RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(left), Arc::new(right)])
        .unwrap()
}

fn make_date64_batch(null_percent: f64) -> RecordBatch {
    let schema = Arc::new(Schema::new(vec![
        Field::new("a", DataType::Date64, true),
        Field::new("b", DataType::Date64, true),
    ]));

    let left = Date64Array::from_iter((0..DATE_ARRAY_LEN).map(|i| {
        (null_percent == 0.0 || i % (1.0 / null_percent) as usize != 0)
            .then_some((18_000 + i as i64) * MILLIS_PER_DAY)
    }));
    let right = Date64Array::from_iter((0..DATE_ARRAY_LEN).map(|i| {
        (null_percent == 0.0 || i % (1.0 / null_percent) as usize != 0)
            .then_some((17_000 + (i % 365) as i64) * MILLIS_PER_DAY)
    }));

    RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(left), Arc::new(right)])
        .unwrap()
}

/// Benchmark Date32 column subtraction.
fn benchmark_date32_subtract(c: &mut Criterion) {
    for (name, null_percent) in [("no_nulls", 0.0), ("20_percent_nulls", 0.2)] {
        let batch = make_date32_batch(null_percent);
        let expr = BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Minus,
            Arc::new(Column::new("b", 1)),
        );

        c.bench_function(&format!("date32_subtract/{name}"), |b| {
            b.iter(|| black_box(expr.evaluate(black_box(&batch)).unwrap()))
        });
    }
}

/// Benchmark Date64 column subtraction.
fn benchmark_date64_subtract(c: &mut Criterion) {
    for (name, null_percent) in [("no_nulls", 0.0), ("20_percent_nulls", 0.2)] {
        let batch = make_date64_batch(null_percent);
        let expr = BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Minus,
            Arc::new(Column::new("b", 1)),
        );

        c.bench_function(&format!("date64_subtract/{name}"), |b| {
            b.iter(|| black_box(expr.evaluate(black_box(&batch)).unwrap()))
        });
    }
}

criterion_group!(
    benches,
    benchmark_binary_op_in_short_circuit,
    benchmark_conjunction,
    benchmark_date32_subtract,
    benchmark_date64_subtract
);

criterion_main!(benches);