datafusion-match-recognize 0.55.0

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
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
// Licensed 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.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

#![cfg(feature = "sql")]

use super::{narrow_sorted_input, optimize};
use std::collections::HashMap;
use std::sync::Arc;

use crate::execution::physical::is_match_recognize_exec;
use datafusion::arrow::array::{BooleanArray, Int32Array};
use datafusion::arrow::compute::concat_batches;
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion::common::{
    Constraint, Constraints, Result, ScalarValue, config::ConfigOptions,
};
use datafusion::datasource::MemTable;
use datafusion::datasource::memory::MemorySourceConfig;
use datafusion::datasource::source::DataSourceExec;
use datafusion::execution::SessionStateBuilder;
use datafusion::logical_expr::Operator;
use datafusion::physical_expr::expressions::{BinaryExpr, Column, Literal};
use datafusion::physical_expr::{LexOrdering, PhysicalExpr, PhysicalSortExpr};
use datafusion::physical_plan::execution_plan::reset_plan_states;
use datafusion::physical_plan::filter::FilterExec;
use datafusion::physical_plan::projection::ProjectionExec;
use datafusion::physical_plan::repartition::RepartitionExec;
use datafusion::physical_plan::sorts::sort::SortExec;
use datafusion::physical_plan::union::UnionExec;
use datafusion::physical_plan::{
    ExecutionPlan, ExecutionPlanProperties, Partitioning, RangePartitioning, SplitPoint,
    collect,
};
use datafusion::prelude::{SessionConfig, SessionContext};

pub(in crate::optimizer) fn context() -> Result<SessionContext> {
    let mut config = SessionConfig::new()
        .with_target_partitions(2)
        .with_batch_size(3);
    config
        .options_mut()
        .extensions
        .insert(crate::MatchRecognizeConfig::default());
    config.options_mut().optimizer.subset_repartition_threshold = 1;
    // Apply the rule explicitly so the reference plan retains its constants.
    let mut state = SessionStateBuilder::new()
        .with_default_features()
        .with_config(config)
        .with_query_planner(crate::advanced::query_planner_with_extensions(vec![]))
        .build();
    crate::advanced::register_state(&mut state)?;
    let ctx = SessionContext::new_with_state(state);
    crate::advanced::register_optimizer_rules(&ctx);
    let schema = Arc::new(Schema::new(vec![
        Field::new("p", DataType::Int32, false)
            .with_metadata(HashMap::from([("origin".into(), "test_case".into())])),
        Field::new("seq", DataType::Int32, false),
        Field::new("v", DataType::Int32, false),
        Field::new("flag", DataType::Boolean, true),
    ]));
    let partitions = [vec![10, 5, 0, 7], vec![2, 3, 4, 5]]
        .into_iter()
        .enumerate()
        .map(|(index, values)| {
            RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Int32Array::from(vec![index as i32 + 1; 4])),
                    Arc::new(Int32Array::from(vec![1, 2, 3, 4])),
                    Arc::new(Int32Array::from(values)),
                    Arc::new(BooleanArray::from(vec![
                        Some(true),
                        None,
                        Some(false),
                        Some(true),
                    ])),
                ],
            )
            .map(|batch| vec![batch])
            .map_err(Into::into)
        })
        .collect::<Result<Vec<_>>>()?;
    ctx.register_table("ticks", Arc::new(MemTable::try_new(schema, partitions)?))?;
    Ok(ctx)
}

async fn plan(ctx: &SessionContext, sql: &str) -> Result<Arc<dyn ExecutionPlan>> {
    ctx.sql(sql).await?.create_physical_plan().await
}

fn matcher_input(plan: &Arc<dyn ExecutionPlan>) -> Option<Arc<dyn ExecutionPlan>> {
    if is_match_recognize_exec(plan.as_ref()) {
        return plan.children().first().map(|child| Arc::clone(child));
    }
    plan.children().into_iter().find_map(matcher_input)
}

fn transport_widths(plan: &Arc<dyn ExecutionPlan>) -> Vec<usize> {
    let mut widths = Vec::new();
    plan.apply(|node| {
        if node.is::<SortExec>() || node.is::<RepartitionExec>() {
            widths.push(node.schema().fields().len());
        }
        Ok(TreeNodeRecursion::Continue)
    })
    .unwrap();
    widths
}

async fn assert_rewrite_preserves_results(ctx: &SessionContext, sql: &str) -> Result<()> {
    let original = plan(ctx, sql).await?;
    let rewritten = optimize(Arc::clone(&original), ctx.state().config_options())?;
    let before = matcher_input(&original).unwrap();
    let after = matcher_input(&rewritten).unwrap();
    assert_eq!(before.schema(), after.schema());
    assert_eq!(original.schema(), rewritten.schema());
    let old_widths = transport_widths(&before);
    let new_widths = transport_widths(&after);
    assert!(!old_widths.is_empty());
    assert_eq!(old_widths.len(), new_widths.len());
    assert!(
        old_widths
            .iter()
            .zip(new_widths)
            .all(|(old, new)| new + 2 <= *old)
    );
    let twice = optimize(Arc::clone(&rewritten), ctx.state().config_options())?;
    assert!(Arc::ptr_eq(&rewritten, &twice));
    let expected = collect(reset_plan_states(original)?, ctx.task_ctx()).await?;
    let actual = collect(reset_plan_states(rewritten)?, ctx.task_ctx()).await?;
    let expected = concat_batches(&expected[0].schema(), &expected)?;
    let actual = concat_batches(&actual[0].schema(), &actual)?;
    assert!(expected.num_rows() > 0);
    assert_eq!(expected, actual);
    Ok(())
}

#[tokio::test]
async fn matcher_constants_move_after_transport_without_changing_results() -> Result<()> {
    let ctx = context()?;
    ctx.sql(
        "CREATE VIEW enriched AS
         SELECT TRUE AS yes, CAST(NULL AS BIGINT) AS nil, p, seq, v FROM ticks",
    )
    .await?;
    assert_rewrite_preserves_results(
        &ctx,
        "SELECT k, yes, nil, n FROM enriched
         MATCH_RECOGNIZE (PARTITION BY p ORDER BY seq
           MEASURES FIRST(p) AS k, FIRST(yes) AS yes, FIRST(nil) AS nil, COUNT(*) AS n
           ONE ROW PER MATCH PATTERN (A B) DEFINE A AS v > 0, B AS TRUE)
         ORDER BY 1, 4",
    )
    .await
}

fn sorted(input: Arc<dyn ExecutionPlan>, name: &str) -> Arc<dyn ExecutionPlan> {
    let column = Arc::new(Column::new(name, input.schema().index_of(name).unwrap()));
    let ordering = LexOrdering::new([PhysicalSortExpr::new_default(column)]).unwrap();
    Arc::new(SortExec::new(ordering, input).with_preserve_partitioning(true))
}

#[tokio::test]
async fn global_merge_and_local_runs_transport_only_nonconstant_columns() -> Result<()> {
    use datafusion::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;

    let ctx = context()?;
    let source = plan(
        &ctx,
        "SELECT TRUE AS flag, p * 10 + seq AS ord, v, CAST(NULL AS DOUBLE) AS val FROM ticks",
    )
    .await?;
    let local = sorted(source, "ord");
    let order = local.downcast_ref::<SortExec>().unwrap().expr().clone();
    let global: Arc<dyn ExecutionPlan> =
        Arc::new(SortPreservingMergeExec::new(order, local).with_fetch(Some(5)));
    let rewritten = narrow_sorted_input(&global, &ConfigOptions::default())?.unwrap();
    let restore = rewritten.downcast_ref::<ProjectionExec>().unwrap();
    let merge = restore
        .input()
        .downcast_ref::<SortPreservingMergeExec>()
        .unwrap();
    assert_eq!(merge.fetch(), Some(5));
    assert_eq!(merge.schema().fields().len(), 2);
    assert_eq!(
        merge
            .input()
            .downcast_ref::<SortExec>()
            .unwrap()
            .schema()
            .fields()
            .len(),
        2
    );
    let expected = collect(global, ctx.task_ctx()).await?;
    let actual = collect(rewritten, ctx.task_ctx()).await?;
    assert_eq!(
        concat_batches(&expected[0].schema(), &expected)?,
        concat_batches(&actual[0].schema(), &actual)?
    );
    Ok(())
}

#[tokio::test]
async fn constant_keys_and_nonliteral_field_contracts_keep_the_original_transport()
-> Result<()> {
    let ctx = context()?;
    let input = plan(
        &ctx,
        "SELECT seq, TRUE AS yes, CAST(NULL AS BIGINT) AS nil FROM ticks",
    )
    .await?;
    let config = ConfigOptions::default();
    let plain = sorted(Arc::clone(&input), "seq");
    assert!(narrow_sorted_input(&plain, &config)?.is_some());
    assert!(Arc::ptr_eq(&plain, &optimize(Arc::clone(&plain), &config)?));

    let constant_sort_key = sorted(Arc::clone(&input), "yes");
    let only_yes = plan(&ctx, "SELECT seq, TRUE AS yes FROM ticks").await?;
    let constant_hash_key = Arc::new(RepartitionExec::try_new(
        only_yes,
        Partitioning::Hash(vec![Arc::new(Column::new("yes", 1))], 2),
    )?);
    let fields = input
        .schema()
        .fields()
        .iter()
        .enumerate()
        .map(|(index, field)| {
            if index == 1 {
                field
                    .as_ref()
                    .clone()
                    .with_metadata(HashMap::from([("meaning".into(), "keep".into())]))
            } else {
                field.as_ref().clone()
            }
        })
        .collect::<Vec<_>>();
    let metadata_schema = Schema::new(fields);
    let columns = input
        .schema()
        .fields()
        .iter()
        .enumerate()
        .map(|(index, field)| {
            (
                Arc::new(Column::new(field.name(), index)) as Arc<dyn PhysicalExpr>,
                field.name().clone(),
            )
        })
        .collect::<Vec<_>>();
    let metadata = Arc::new(ProjectionExec::try_new_with_schema_metadata(
        columns,
        Arc::clone(&input),
        &metadata_schema,
    )?);
    let nullable = plan(&ctx, "SELECT seq, flag FROM ticks WHERE flag = TRUE").await?;
    assert!(nullable.schema().field(1).is_nullable());
    for input in [
        constant_sort_key,
        sorted(constant_hash_key, "seq"),
        sorted(metadata, "seq"),
        sorted(nullable, "seq"),
    ] {
        assert!(narrow_sorted_input(&input, &config)?.is_none());
    }

    let schema = Arc::new(Schema::new(vec![
        Field::new("seq", DataType::Int32, false),
        Field::new("part", DataType::Int32, false),
    ]));
    let batch = RecordBatch::try_new(
        Arc::clone(&schema),
        vec![
            Arc::new(Int32Array::from(vec![1, 2, 3])),
            Arc::new(Int32Array::from(vec![0, 0, 0])),
        ],
    )?;
    let source = MemorySourceConfig::try_new(&[vec![batch]], schema, None)?;
    let constrained = Arc::new(DataSourceExec::new(Arc::new(source)).with_constraints(
        Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0, 1])]),
    ));
    let columns: Vec<(Arc<dyn PhysicalExpr>, String)> = vec![
        (Arc::new(Column::new("seq", 0)), "seq".into()),
        (
            Arc::new(Literal::new(ScalarValue::Boolean(Some(true)))),
            "yes".into(),
        ),
        (
            Arc::new(Literal::new(ScalarValue::Int64(None))),
            "nil".into(),
        ),
    ];
    let projected: Arc<dyn ExecutionPlan> =
        Arc::new(ProjectionExec::try_new(columns, constrained)?);
    // Union removes root uniqueness while preserving constant facts. The
    // native projection below it still encounters the constrained source.
    let union = UnionExec::try_new(vec![Arc::clone(&projected), projected])?;
    let input = sorted(union, "seq");
    assert!(input.equivalence_properties().constraints().is_empty());
    assert!(narrow_sorted_input(&input, &config)?.is_none());
    Ok(())
}

#[tokio::test]
async fn unknown_and_unsupported_constant_values_are_not_reconstructed() -> Result<()> {
    let ctx = context()?;
    for sql in [
        "SELECT seq, flag FROM ticks",
        "SELECT seq, 7::BIGINT AS number FROM ticks",
        "SELECT seq, 'constant' AS text FROM ticks",
    ] {
        let input = sorted(plan(&ctx, sql).await?, "seq");
        assert!(narrow_sorted_input(&input, &ConfigOptions::default())?.is_none());
    }
    Ok(())
}

mod stateful;

#[tokio::test]
async fn grouped_payload_restores_constants_and_filter_indices_across_batches()
-> Result<()> {
    use datafusion_hash_grouped_order::{
        BooleanColumnsMaskFilter, HashGroupedOrderConfig, HashGroupedOrderExec,
    };
    use futures::TryStreamExt;
    let ctx = context()?;
    let raw = plan(
        &ctx,
        "SELECT TRUE AS yes, p, seq, v, flag, CAST(NULL AS BIGINT) AS nil FROM ticks",
    )
    .await?;
    let schema = raw.schema();
    let key: Arc<dyn PhysicalExpr> = Arc::new(Column::new_with_schema("p", &schema)?);
    let seq: Arc<dyn PhysicalExpr> = Arc::new(Column::new_with_schema("seq", &schema)?);
    let filter = BooleanColumnsMaskFilter::try_new([schema.index_of("flag")?])?;
    let full: Arc<dyn ExecutionPlan> = Arc::new(
        HashGroupedOrderExec::try_new(
            raw,
            vec![key],
            vec![PhysicalSortExpr::new_default(seq)],
            HashGroupedOrderConfig {
                target_batch_size: Some(2),
                ..Default::default()
            },
        )?
        .with_partition_filter(Arc::new(filter))?,
    );
    let narrow = narrow_sorted_input(&full, &ConfigOptions::default())?
        .expect("Two uniform columns can be restored");
    let full = full.downcast_ref::<HashGroupedOrderExec>().unwrap();
    let slim = narrow
        .downcast_ref::<HashGroupedOrderExec>()
        .expect("range-producing child");
    assert_eq!(slim.input().schema().fields().len(), 4);
    assert_eq!(slim.schema(), schema);
    assert_eq!(
        slim.partition_filter().unwrap().referenced_columns(),
        vec![3]
    );
    for partition in 0..full.input().output_partitioning().partition_count() {
        let expected = full
            .execute_grouped(partition, ctx.task_ctx())?
            .try_collect::<Vec<_>>()
            .await?;
        let actual = slim
            .execute_grouped(partition, ctx.task_ctx())?
            .try_collect::<Vec<_>>()
            .await?;
        assert_eq!(actual.len(), 2);
        assert_eq!(actual.len(), expected.len());
        for (a, b) in actual.iter().zip(expected.iter()) {
            assert_eq!(a.batch, b.batch);
            assert_eq!(a.partition_ranges, b.partition_ranges);
        }
    }
    let reset = reset_plan_states(narrow)?;
    assert_eq!(reset.schema(), schema);
    Ok(())
}

#[tokio::test]
async fn partitioned_sort_and_group_preserve_constant_partition_keys() -> Result<()> {
    use datafusion_hash_grouped_order::{HashGroupedOrderConfig, HashGroupedOrderExec};

    let ctx = context()?;
    let config = ConfigOptions::default();
    let seq_gt_zero: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
        Arc::new(Column::new("seq", 0)),
        Operator::Gt,
        Arc::new(Literal::new(ScalarValue::Int32(Some(0)))),
    ));

    // Sole constant is the Hash partition key under a FilterExec child:
    // narrow_sorted_input must not drop it or degrade Hash to UnKnownColumn.
    let only_yes = plan(&ctx, "SELECT seq, TRUE AS yes FROM ticks").await?;
    let hash_yes = Partitioning::Hash(vec![Arc::new(Column::new("yes", 1))], 2);
    let filtered_only_yes = Arc::new(FilterExec::try_new(
        Arc::clone(&seq_gt_zero),
        Arc::new(RepartitionExec::try_new(only_yes, hash_yes.clone())?),
    )?);
    let sort_only_yes = sorted(filtered_only_yes, "seq");
    assert_eq!(sort_only_yes.output_partitioning(), &hash_yes);
    assert!(narrow_sorted_input(&sort_only_yes, &config)?.is_none());

    // With an extra constant alongside a constant Hash or Range partition key
    // under FilterExec, narrow only the non-key constant and keep partitioning exact.
    let with_extra = plan(
        &ctx,
        "SELECT seq, TRUE AS yes, CAST(NULL AS BIGINT) AS nil FROM ticks",
    )
    .await?;
    let range_yes = Partitioning::Range(RangePartitioning::try_new(
        LexOrdering::new([PhysicalSortExpr::new_default(Arc::new(Column::new(
            "yes", 1,
        )))])
        .unwrap(),
        vec![SplitPoint::new(vec![ScalarValue::Boolean(Some(true))])],
    )?);
    let hash_nil = Partitioning::Hash(vec![Arc::new(Column::new("nil", 2))], 2);
    for partitioning in [hash_yes.clone(), hash_nil, range_yes] {
        let repart = Arc::new(RepartitionExec::try_new(
            Arc::clone(&with_extra),
            partitioning.clone(),
        )?);
        let filtered = Arc::new(FilterExec::try_new(Arc::clone(&seq_gt_zero), repart)?);
        let sort = sorted(filtered, "seq");
        assert_eq!(sort.output_partitioning(), &partitioning);
        let restored = narrow_sorted_input(&sort, &config)?
            .expect("unrelated constant should narrow while keeping partition key");
        assert_eq!(restored.schema(), sort.schema());
        assert_eq!(restored.output_partitioning(), &partitioning);
        let projection = restored.downcast_ref::<ProjectionExec>().unwrap();
        let narrow_sort = projection.input().downcast_ref::<SortExec>().unwrap();
        assert_eq!(narrow_sort.schema().fields().len(), 2);
    }

    // HashGroupedOrderExec sibling path: preserve a constant Hash key even when
    // it is not part of partition_by or order_by.
    let repart = Arc::new(RepartitionExec::try_new(with_extra, hash_yes.clone())?);
    let seq_col: Arc<dyn PhysicalExpr> = Arc::new(Column::new("seq", 0));
    let grouped: Arc<dyn ExecutionPlan> = Arc::new(HashGroupedOrderExec::try_new(
        repart,
        vec![Arc::clone(&seq_col)],
        vec![PhysicalSortExpr::new_default(seq_col)],
        HashGroupedOrderConfig::default(),
    )?);
    assert_eq!(grouped.output_partitioning(), &hash_yes);
    let narrowed = narrow_sorted_input(&grouped, &config)?
        .expect("unrelated constant should narrow while keeping grouped Hash key");
    assert_eq!(narrowed.output_partitioning(), &hash_yes);
    let slim = narrowed.downcast_ref::<HashGroupedOrderExec>().unwrap();
    assert_eq!(slim.input().schema().fields().len(), 2);
    Ok(())
}