datafusion-match-recognize 0.56.1

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
// 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.

use super::*;
use crate::config::MatchRecognizeConfig;
use crate::core::NormalizedPattern;
use crate::core::{
    EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeOutputSpec, Pattern,
    RowsPerMatch, Symbol, SymbolId,
};
use crate::execution::matching::{
    ExecutableMatchProgram, ExecutableOutputPlan, ResolvedAfterMatchSkip,
    ResolvedBoolColumn, SymbolColumn, static_test_program, test_executable_input,
    test_symbol_programs_for_automaton,
};
use crate::execution::physical::PartitionRetention;
use crate::execution::stream::MatchInput;
use crate::nfa::CompiledAutomaton;
use crate::planning::SymbolRelationships;
use datafusion::arrow::array::{ArrayRef, BooleanArray, Int32Array};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::ScalarValue;
use datafusion::execution::TaskContext;
use datafusion::logical_expr::Operator;
use datafusion::physical_expr::expressions::{BinaryExpr, Column, Literal};
use datafusion::physical_plan::PhysicalExpr;
use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
use futures::TryStreamExt;

fn build_static_tail_program(
    predicate: Arc<dyn PhysicalExpr>,
) -> Result<(Arc<Schema>, ExecutableMatchProgram)> {
    let schema = Arc::new(Schema::new(vec![
        Field::new("v", DataType::Int32, false),
        Field::new("__mr_symbol_a", DataType::Boolean, false),
        Field::new("__mr_symbol_b", DataType::Boolean, false),
    ]));
    let pattern = Pattern::Concat(vec![
        Pattern::Symbol(Symbol::Named("A".into())),
        Pattern::Symbol(Symbol::Named("B".into())),
    ]);
    let normalized = NormalizedPattern::Ast(pattern);
    let automaton = Arc::new(CompiledAutomaton::compile(
        &normalized,
        &["A".into(), "B".into()],
    )?);
    assert_eq!(automaton.min_match_rows(), 2);
    let sym_a = SymbolId::try_new(1, automaton.num_symbols()).unwrap();
    let sym_b = SymbolId::try_new(2, automaton.num_symbols()).unwrap();
    let output = ExecutableOutputPlan::try_rows(
        schema.as_ref(),
        MatchRecognizeOutputSpec::new(
            vec![0],
            vec![MatchMetadataColumn::MatchNumber],
            vec![],
        ),
        Arc::from([]),
        RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
        automaton.as_ref(),
    )?;
    let mut input = test_executable_input(
        Arc::clone(&schema),
        normalized,
        Arc::clone(&automaton),
        vec![],
        ResolvedAfterMatchSkip::PastLastRow,
    );
    input.output = output;
    let predicate_b = Arc::new(BinaryExpr::new(
        Arc::new(Column::new("v", 0)),
        Operator::Gt,
        Arc::new(Literal::new(ScalarValue::Int32(Some(100)))),
    )) as Arc<dyn PhysicalExpr>;
    input.symbols.symbol_programs = test_symbol_programs_for_automaton(
        &automaton,
        &[(sym_a, predicate), (sym_b, predicate_b)],
        0,
    );
    let program = ExecutableMatchProgram::try_new(input)?;
    assert!(!program.can_skip_candidate_evaluation);
    Ok((schema, program))
}

async fn run_static_tail_case(
    schema: &Arc<Schema>,
    program: &ExecutableMatchProgram,
    values: Vec<i32>,
    disable_compact_paths: bool,
) -> Result<Vec<RecordBatch>> {
    let rows = values.len();
    let batch = RecordBatch::try_new(
        Arc::clone(schema),
        vec![
            Arc::new(Int32Array::from(values)) as ArrayRef,
            Arc::new(BooleanArray::from(vec![false; rows])),
            Arc::new(BooleanArray::from(vec![false; rows])),
        ],
    )?;
    let input = Box::pin(RecordBatchStreamAdapter::new(
        Arc::clone(schema),
        futures::stream::iter(vec![Ok(batch)]),
    ));
    let mut config = MatchRecognizeConfig::default();
    config.diagnostics.disable_compact_paths = disable_compact_paths;
    let stream = match_aware_stream(
        ExecutePatternInput {
            input: MatchInput::Ordered(input),
            program: Arc::new(program.clone()),
            partition_by_sort_keys: vec![],
            retention: PartitionRetention::ThresholdSafe,
            candidate_start_core_rows: None,
            output_batch_size: None,
            flush_threshold: 1024,
            config,
            metrics_set: ExecutionPlanMetricsSet::new(),
            task_context: Arc::new(TaskContext::default()),
            partition: 0,
        },
        SliceControl::default(),
    )?;
    stream.try_collect().await
}

#[tokio::test]
async fn unified_stream_preserves_fallible_define_on_short_and_trailing_min_match_rows_tails()
-> Result<()> {
    let ratio = BinaryExpr::new(
        Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
        Operator::Divide,
        Arc::new(Column::new("v", 0)),
    );
    let predicate = BinaryExpr::new(
        Arc::new(ratio),
        Operator::Gt,
        Arc::new(Literal::new(ScalarValue::Int32(Some(0)))),
    );
    let (schema, program) = build_static_tail_program(Arc::new(predicate))?;

    for (label, values) in [
        ("one-row partition", vec![0_i32]),
        ("trailing row after failed start", vec![1, 0]),
        ("trailing row after match", vec![1, 200, 0]),
    ] {
        for disable_compact_paths in [false, true] {
            let Err(err) = run_static_tail_case(
                &schema,
                &program,
                values.clone(),
                disable_compact_paths,
            )
            .await
            else {
                panic!(
                    "{label} (disable_compact_paths={disable_compact_paths}) must raise divide by zero"
                );
            };
            assert!(
                err.to_string()
                    .to_ascii_lowercase()
                    .contains("divide by zero"),
                "{label} (disable_compact_paths={disable_compact_paths}) unexpected error: {err}"
            );
        }
    }
    Ok(())
}

#[tokio::test]
async fn unified_stream_finishes_closed_lazy_define_on_short_tails_without_error()
-> Result<()> {
    let predicate = BinaryExpr::new(
        Arc::new(Column::new("v", 0)),
        Operator::Gt,
        Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
    );
    let (schema, program) = build_static_tail_program(Arc::new(predicate))?;
    assert!(!program.can_skip_candidate_evaluation);

    for values in [vec![1_i32], vec![1, 2]] {
        let batches = run_static_tail_case(&schema, &program, values, false).await?;
        let total_rows: usize = batches.iter().map(RecordBatch::num_rows).sum();
        assert_eq!(total_rows, 0);
    }
    Ok(())
}

fn build_static_unmatched_program(
    pattern: Pattern,
) -> Result<(Arc<Schema>, ExecutableMatchProgram)> {
    let schema = Arc::new(Schema::new(vec![
        Field::new("v", DataType::Int32, false),
        Field::new("__mr_symbol_a", DataType::Boolean, false),
    ]));
    let normalized = NormalizedPattern::Ast(pattern);
    let automaton = Arc::new(CompiledAutomaton::compile(&normalized, &["A".into()])?);
    let sym_a = SymbolId::try_new(1, automaton.num_symbols()).unwrap();
    let symbols = vec![SymbolColumn {
        id: sym_a,
        column: ResolvedBoolColumn::new_validated(1),
    }];
    let output = ExecutableOutputPlan::try_rows(
        schema.as_ref(),
        MatchRecognizeOutputSpec::new(
            vec![0],
            vec![
                MatchMetadataColumn::MatchNumber,
                MatchMetadataColumn::Classifier,
            ],
            vec![],
        ),
        Arc::from([]),
        RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched),
        automaton.as_ref(),
    )?;
    let program = static_test_program(
        Arc::clone(&schema),
        normalized,
        automaton,
        symbols,
        ResolvedAfterMatchSkip::PastLastRow,
        output,
        SymbolRelationships::default(),
    )?;
    Ok((schema, program))
}

#[tokio::test]
async fn unified_stream_bounds_unmatched_batches_and_memory_on_closed_and_extended_partitions()
-> Result<()> {
    use datafusion::arrow::array::{Array, Int64Array, StringArray};
    use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool};
    use datafusion::execution::runtime_env::RuntimeEnvBuilder;

    const FLUSH_THRESHOLD: usize = 64;

    // 1. Closed sole partition (`LogicalPartitionBoundaryOnly` with `$`-anchored
    //    `A $`, `!next_closed`) and 2. Multi-head open-then-closed partition
    //    (`ThresholdSafe` exercising `Extend` + `FinishClosed`).
    let cases = [
        (
            "closed sole partition",
            Pattern::Concat(vec![
                Pattern::Symbol(Symbol::Named("A".into())),
                Pattern::Symbol(Symbol::End),
            ]),
            PartitionRetention::LogicalPartitionBoundaryOnly,
            256usize,
            128usize,
            1024 * 1024,
        ),
        (
            "extended open partition",
            Pattern::Symbol(Symbol::Named("A".into())),
            PartitionRetention::ThresholdSafe,
            2usize,
            8_192usize,
            384 * 1024,
        ),
    ];

    for (label, pattern, retention, num_batches, batch_rows, pool_limit) in cases {
        let total_rows = num_batches * batch_rows;
        let (schema, program) = build_static_unmatched_program(pattern)?;
        let mut input_batches = Vec::with_capacity(num_batches);
        for b in 0..num_batches {
            let start = (b * batch_rows) as i32;
            let end = start + batch_rows as i32;
            input_batches.push(Ok(RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Int32Array::from_iter_values(start..end)) as ArrayRef,
                    Arc::new(BooleanArray::from(vec![false; batch_rows])),
                ],
            )?));
        }
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(pool_limit));
        let runtime = Arc::new(
            RuntimeEnvBuilder::new()
                .with_memory_pool(Arc::clone(&pool))
                .build()?,
        );
        let task_context = Arc::new(TaskContext::default().with_runtime(runtime));
        let input = Box::pin(RecordBatchStreamAdapter::new(
            Arc::clone(&schema),
            futures::stream::iter(input_batches),
        ));
        let mut stream = match_aware_stream(
            ExecutePatternInput {
                input: MatchInput::Ordered(input),
                program: Arc::new(program),
                partition_by_sort_keys: vec![],
                retention,
                candidate_start_core_rows: None,
                output_batch_size: None,
                flush_threshold: FLUSH_THRESHOLD,
                config: MatchRecognizeConfig::default(),
                metrics_set: ExecutionPlanMetricsSet::new(),
                task_context,
                partition: 0,
            },
            SliceControl::default(),
        )?;

        let mut emitted_batches = 0usize;
        let mut next_expected = 0i32;
        while let Some(batch) = stream.try_next().await? {
            emitted_batches += 1;
            assert!(
                batch.num_rows() <= FLUSH_THRESHOLD,
                "{label}: emitted batch had {} rows, exceeding flush_threshold {FLUSH_THRESHOLD}",
                batch.num_rows()
            );
            let values = batch
                .column_by_name("v")
                .unwrap()
                .as_any()
                .downcast_ref::<Int32Array>()
                .unwrap();
            let match_nums = batch
                .column_by_name(MatchMetadataColumn::MatchNumber.as_ref())
                .unwrap()
                .as_any()
                .downcast_ref::<Int64Array>()
                .unwrap();
            let classifiers = batch
                .column_by_name(MatchMetadataColumn::Classifier.as_ref())
                .unwrap()
                .as_any()
                .downcast_ref::<StringArray>()
                .unwrap();
            for row in 0..batch.num_rows() {
                assert_eq!(values.value(row), next_expected);
                assert!(match_nums.is_null(row));
                assert!(classifiers.is_null(row));
                next_expected += 1;
            }
        }
        assert_eq!(next_expected as usize, total_rows, "{label}");
        assert_eq!(
            emitted_batches,
            total_rows.div_ceil(FLUSH_THRESHOLD),
            "{label}"
        );
        drop(stream);
        assert_eq!(pool.reserved(), 0, "{label}: leaked pool bytes");
    }
    Ok(())
}

#[tokio::test]
async fn unified_stream_preserves_virtual_eof_match_with_bounded_unmatched_batches()
-> Result<()> {
    use crate::core::RepetitionQuantifier;
    use datafusion::arrow::array::{Array, Int64Array, StringArray};

    const ROWS: usize = 130;
    const FLUSH_THRESHOLD: usize = 32;
    let pattern = Pattern::Concat(vec![
        Pattern::Repetition(
            Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
            RepetitionQuantifier::ZeroOrMore,
        ),
        Pattern::Symbol(Symbol::End),
    ]);
    let (schema, program) = build_static_unmatched_program(pattern)?;
    let batch = RecordBatch::try_new(
        Arc::clone(&schema),
        vec![
            Arc::new(Int32Array::from_iter_values(0..ROWS as i32)) as ArrayRef,
            Arc::new(BooleanArray::from(vec![false; ROWS])),
        ],
    )?;
    let input = Box::pin(RecordBatchStreamAdapter::new(
        Arc::clone(&schema),
        futures::stream::iter(vec![Ok(batch)]),
    ));
    let stream = match_aware_stream(
        ExecutePatternInput {
            input: MatchInput::Ordered(input),
            program: Arc::new(program),
            partition_by_sort_keys: vec![],
            retention: PartitionRetention::LogicalPartitionBoundaryOnly,
            candidate_start_core_rows: None,
            output_batch_size: None,
            flush_threshold: FLUSH_THRESHOLD,
            config: MatchRecognizeConfig::default(),
            metrics_set: ExecutionPlanMetricsSet::new(),
            task_context: Arc::new(TaskContext::default()),
            partition: 0,
        },
        SliceControl::default(),
    )?;
    let batches: Vec<RecordBatch> = stream.try_collect().await?;
    assert!(batches.len() >= 5);
    for batch in &batches {
        assert!(
            batch.num_rows() <= FLUSH_THRESHOLD,
            "batch exceeded flush_threshold: {}",
            batch.num_rows()
        );
    }
    let combined =
        datafusion::arrow::compute::concat_batches(&batches[0].schema(), &batches)?;
    assert_eq!(combined.num_rows(), ROWS);
    let values = combined
        .column_by_name("v")
        .unwrap()
        .as_any()
        .downcast_ref::<Int32Array>()
        .unwrap();
    let match_nums = combined
        .column_by_name(MatchMetadataColumn::MatchNumber.as_ref())
        .unwrap()
        .as_any()
        .downcast_ref::<Int64Array>()
        .unwrap();
    let classifiers = combined
        .column_by_name(MatchMetadataColumn::Classifier.as_ref())
        .unwrap()
        .as_any()
        .downcast_ref::<StringArray>()
        .unwrap();
    for row in 0..ROWS {
        assert_eq!(
            values.is_valid(row).then(|| values.value(row)),
            Some(row as i32)
        );
        assert!(match_nums.is_null(row));
        assert!(classifiers.is_null(row));
    }
    Ok(())
}