datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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
// 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.

//! Closed SQL partitions share an output batch without sharing match state.

use super::{TestPlanSpec, build_test_exec};
use crate::core::{
    EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeOutputSpec, MatchSummaryField,
    Pattern, RepetitionQuantifier, RowsPerMatch, Symbol, SymbolId,
};
use crate::execution::common::scheduling::{SliceControl, with_active_slice};
use crate::execution::matching::{ExecutableDirectCountSummary, OutputPartitionBindings};
use crate::execution::physical::PartitionRetention;
use crate::execution::stream::stateful_stream::match_aware_stream;
use crate::nfa_executor::ExecutePatternInput;
use datafusion::arrow::array::{BooleanArray, Int32Array, Int64Array};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::scalar::ScalarValue;
use datafusion_common::{DataFusionError, Result};
use datafusion_execution::RecordBatchStream;
use datafusion_physical_expr::PhysicalExpr;
use datafusion_physical_expr::expressions::Column;
use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
use datafusion_physical_plan::SendableRecordBatchStream;
use datafusion_physical_plan::empty::EmptyExec;
use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
use futures::TryStreamExt;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::task::{Context, Poll};
use std::time::Duration;

//12 partitions include the deliberate7/11-period NULL and all-NULL controls.
const PARTITIONS: usize = 12;
const ROWS_PER_PARTITION: usize = 6;
const SELECTED_ROWS: usize = PARTITIONS * 4;

#[derive(Clone, Copy, Debug)]
enum Output {
    Rows,
    RowsWithUnmatched,
    DirectCount,
}

fn value(partition: usize, position: usize) -> Option<i64> {
    // Include NULL arguments and complete all-NULL matches. Keeping them beside
    // non-NULL groups catches a summary group leaking across a SQL boundary.
    if (partition + position).is_multiple_of(7)
        || (partition.is_multiple_of(11) && matches!(position, 3 | 4))
    {
        None
    } else {
        Some((partition * 10 + position) as i64 - 1000)
    }
}

fn input_batch() -> Result<RecordBatch> {
    let schema = Arc::new(Schema::new(vec![
        Field::new("p", DataType::Int32, false),
        Field::new("x", DataType::Int64, true),
        Field::new("__mr_symbol_a", DataType::Boolean, false),
    ]));
    let mut keys = Vec::new();
    let mut values = Vec::new();
    let mut predicates = Vec::new();
    for partition in 0..PARTITIONS {
        for position in 0..ROWS_PER_PARTITION {
            keys.push(partition as i32);
            values.push(value(partition, position));
            predicates.push(matches!(position, 0 | 1 | 3 | 4));
        }
    }
    Ok(RecordBatch::try_new(
        schema,
        vec![
            Arc::new(Int32Array::from(keys)),
            Arc::new(Int64Array::from(values)),
            Arc::new(BooleanArray::from(predicates)),
        ],
    )?)
}

fn install_output(spec: &mut TestPlanSpec, output: Output) -> Result<()> {
    match output {
        Output::Rows | Output::RowsWithUnmatched => {
            spec.rows_per_match = RowsPerMatch::AllRows(match output {
                Output::Rows => EmptyMatchesMode::Omit,
                Output::RowsWithUnmatched => EmptyMatchesMode::WithUnmatched,
                Output::DirectCount => unreachable!(),
            });
            spec.output_spec = MatchRecognizeOutputSpec::new(
                vec![0, 1],
                vec![
                    MatchMetadataColumn::Classifier,
                    MatchMetadataColumn::MatchNumber,
                    MatchMetadataColumn::MatchSequenceNumber,
                ],
                vec![],
            );
        }
        Output::DirectCount => {
            spec.output_spec = MatchRecognizeOutputSpec::new(
                vec![0],
                vec![MatchMetadataColumn::MatchNumber],
                vec![],
            );
            spec.selected_match_summary = Some(vec![ExecutableDirectCountSummary::new(
                MatchSummaryField::new(
                    0,
                    Arc::new(Field::new("count", DataType::Int64, false)),
                ),
                Some(SymbolId::try_new(1, 2).unwrap()),
            )]);
        }
    }
    Ok(())
}

fn expected_rows(output: Output) -> Vec<Vec<ScalarValue>> {
    let mut rows = Vec::new();
    for partition in 0..PARTITIONS {
        let key = ScalarValue::Int32(Some(partition as i32));
        for (number, positions) in [(1, [0, 1]), (2, [3, 4])] {
            let match_number = ScalarValue::Int64(Some(number));
            match output {
                Output::Rows | Output::RowsWithUnmatched => {
                    for (sequence, position) in positions.into_iter().enumerate() {
                        rows.push(vec![
                            key.clone(),
                            ScalarValue::Int64(value(partition, position)),
                            ScalarValue::Utf8(Some("A".to_string())),
                            match_number.clone(),
                            ScalarValue::Int64(Some(sequence as i64 + 1)),
                        ]);
                    }
                }
                Output::DirectCount => {
                    rows.push(vec![
                        key.clone(),
                        match_number,
                        ScalarValue::Int64(Some(2)),
                    ]);
                }
            }
            if matches!(output, Output::RowsWithUnmatched) {
                rows.push(vec![
                    key.clone(),
                    ScalarValue::Int64(value(partition, positions[1] + 1)),
                    ScalarValue::Utf8(None),
                    ScalarValue::Int64(None),
                    ScalarValue::Int64(None),
                ]);
            }
        }
    }
    rows
}

async fn collect_output(
    batch: &RecordBatch,
    output: Output,
    cuts: &[usize],
    threshold: usize,
    sliced: bool,
) -> Result<Vec<RecordBatch>> {
    let mut input = Vec::new();
    let mut start = 0;
    for end in cuts.iter().copied().chain([batch.num_rows()]) {
        input.push(Ok(batch.slice(start, end - start)));
        start = end;
    }
    let (stream, slice) = build_stream(
        Box::pin(RecordBatchStreamAdapter::new(
            batch.schema(),
            futures::stream::iter(input),
        )),
        output,
        threshold,
    )?;
    with_active_slice(stream, slice, sliced.then_some(Duration::from_micros(1)))
        .try_collect()
        .await
}

fn build_stream(
    input: SendableRecordBatchStream,
    output: Output,
    threshold: usize,
) -> Result<(impl RecordBatchStream + Unpin, SliceControl)> {
    let schema = input.schema();
    let key = Arc::new(Column::new("p", 0)) as Arc<dyn PhysicalExpr>;
    let mut spec = TestPlanSpec::new(Arc::new(EmptyExec::new(Arc::clone(&schema))));
    spec.pattern = Pattern::Repetition(
        Box::new(Pattern::Symbol(Symbol::Named("A".to_string()))),
        RepetitionQuantifier::OneOrMore,
    );
    spec.partition_by = vec![Arc::clone(&key)];
    install_output(&mut spec, output)?;
    let exec = build_test_exec(spec)?;
    let output_bindings = OutputPartitionBindings::try_new(
        schema.as_ref(),
        exec.program().output_plan(),
        [Arc::clone(&key)],
    )?;
    let slice = SliceControl::default();
    let stream = match_aware_stream(
        ExecutePatternInput {
            input: crate::execution::stream::MatchInput::Ordered(input),
            program: Arc::clone(exec.program()),
            output_bindings,
            partition_by_sort_keys: vec![PhysicalSortExpr::new_default(key)],
            retention: PartitionRetention::ThresholdSafe,
            candidate_start_core_rows: None,
            output_batch_size: None,
            flush_threshold: threshold,
            config: Default::default(),
            metrics_set: ExecutionPlanMetricsSet::new(),
            task_context: Arc::new(datafusion_execution::TaskContext::default()),
            partition: 0,
        },
        slice.clone(),
    )?;
    Ok((stream, slice))
}

fn typed_rows(batches: &[RecordBatch]) -> Result<Vec<Vec<ScalarValue>>> {
    let mut rows = Vec::new();
    for batch in batches {
        for row in 0..batch.num_rows() {
            rows.push(
                batch
                    .columns()
                    .iter()
                    .map(|column| ScalarValue::try_from_array(column, row))
                    .collect::<Result<Vec<_>>>()?,
            );
        }
    }
    Ok(rows)
}

async fn check_output(output: Output) -> Result<()> {
    let batch = input_batch()?;
    let expected = expected_rows(output);
    for (cuts, threshold, sliced) in [
        (&[][..], 7, false),
        (&[1, 13, 37, 61][..], 8192, true),
        (&[2, 6][..], 7, true),
    ] {
        let batches = collect_output(&batch, output, cuts, threshold, sliced).await?;
        let case =
            format!("{output:?}, cuts={cuts:?}, threshold={threshold}, sliced={sliced}");
        // Permit threshold flushes and input-owner retirement, never
        // one materialization per SQL partition or voluntary yield.
        // Private summary rows use the same budget, so base the bound
        // on selected input rows rather than the smaller summary output.
        let budgeted_rows = match output {
            Output::RowsWithUnmatched => PARTITIONS * ROWS_PER_PARTITION,
            Output::Rows | Output::DirectCount => SELECTED_ROWS,
        };
        let max_batches = budgeted_rows.div_ceil(threshold) + cuts.len() + 1;
        assert!(
            batches.len() <= max_batches,
            "{case}: {} output batches exceed {max_batches}",
            batches.len()
        );
        for batch in &batches {
            assert!(batch.num_rows() > 0, "{case}: empty output batch");
        }
        // Preserve stream order: sorting here would conceal reordered
        // partitions, repeated match numbers, or cross-key summaries.
        assert_eq!(typed_rows(&batches)?, expected, "{case}");
    }
    Ok(())
}

#[tokio::test]
async fn closed_partitions_batch_each_output_kind_without_sharing_state() -> Result<()> {
    for output in [Output::Rows, Output::RowsWithUnmatched, Output::DirectCount] {
        check_output(output).await?;
    }
    Ok(())
}

#[tokio::test]
async fn closed_partitions_batch_retained_history_before_retiring_its_head() -> Result<()>
{
    let schema = Arc::new(Schema::new(vec![
        Field::new("p", DataType::Int32, true),
        Field::new("x", DataType::Int64, false),
        Field::new("__mr_symbol_a", DataType::Boolean, false),
    ]));
    let keys = [
        vec![None; 9],
        vec![Some(1); 2],
        vec![Some(2); 2],
        vec![Some(3)],
    ]
    .concat();
    let batch = RecordBatch::try_new(
        schema,
        vec![
            Arc::new(Int32Array::from(keys)),
            Arc::new(Int64Array::from_iter_values(0_i64..14)),
            Arc::new(BooleanArray::from(
                (0..14).map(|row| row < 13).collect::<Vec<_>>(),
            )),
        ],
    )?;
    let mut expected = Vec::new();
    for (key, rows) in [(None, 0_i64..9), (Some(1), 9..11), (Some(2), 11..13)] {
        for (sequence, value) in rows.enumerate() {
            expected.push(vec![
                ScalarValue::Int32(key),
                ScalarValue::Int64(Some(value)),
                ScalarValue::Utf8(Some("A".to_string())),
                ScalarValue::Int64(Some(1)),
                ScalarValue::Int64(Some(sequence as i64 + 1)),
            ]);
        }
    }
    for (cut, sliced) in [(8, false), (9, true)] {
        // At eight rows, NULL resumes across heads. At nine, the changed
        // key leaves the next closed partition in pending_segment. Both
        // retain one output row from history after the first full batch,
        // then combine it with rows from the next head's closed keys.
        let batches = collect_output(&batch, Output::Rows, &[cut], 8, sliced).await?;
        assert_eq!(
            batches
                .iter()
                .map(RecordBatch::num_rows)
                .collect::<Vec<_>>(),
            vec![8, 5],
            "cut={cut}, sliced={sliced}: flushed the retained-history tail early"
        );
        assert_eq!(
            typed_rows(&batches)?,
            expected,
            "cut={cut}, sliced={sliced}: lost history or partition metadata"
        );
    }
    Ok(())
}

fn poll_ready(
    stream: &mut SendableRecordBatchStream,
    context: &mut Context<'_>,
) -> Option<Result<RecordBatch>> {
    (0..4096)
        .find_map(|_| match stream.as_mut().poll_next(context) {
            Poll::Ready(value) => Some(value),
            Poll::Pending => None,
        })
        .expect("bounded static stream polling must reach an output or terminal result")
}

#[tokio::test]
async fn closed_partitions_publish_before_polling_a_pending_open_tail() -> Result<()> {
    let schema = Arc::new(Schema::new(vec![
        Field::new("p", DataType::Int32, false),
        Field::new("x", DataType::Int64, false),
        Field::new("__mr_symbol_a", DataType::Boolean, false),
    ]));
    let batch = RecordBatch::try_new(
        Arc::clone(&schema),
        vec![
            Arc::new(Int32Array::from_iter_values((0..5).map(|row| row / 2))),
            Arc::new(Int64Array::from_iter_values(0_i64..5)),
            Arc::new(BooleanArray::from(vec![true; 5])),
        ],
    )?;
    let sliced = true;
    let polls = Arc::new(AtomicUsize::new(0));
    let fail = Arc::new(AtomicBool::new(false));
    let observed_polls = Arc::clone(&polls);
    let inject_failure = Arc::clone(&fail);
    let mut first_input = Some(batch.clone());
    let source = futures::stream::poll_fn(move |_| {
        observed_polls.fetch_add(1, Ordering::SeqCst);
        if let Some(batch) = first_input.take() {
            Poll::Ready(Some(Ok(batch)))
        } else if inject_failure.swap(false, Ordering::SeqCst) {
            Poll::Ready(Some(Err(DataFusionError::Execution(
                "injected upstream failure".to_string(),
            ))))
        } else {
            Poll::Pending
        }
    });
    let (stream, slice) = build_stream(
        Box::pin(RecordBatchStreamAdapter::new(Arc::clone(&schema), source)),
        Output::Rows,
        8,
    )?;
    let mut stream: SendableRecordBatchStream = Box::pin(with_active_slice(
        stream,
        slice,
        sliced.then_some(Duration::from_micros(1)),
    ));
    let waker = futures::task::noop_waker();
    let mut context = Context::from_waker(&waker);
    let output = poll_ready(&mut stream, &mut context)
        .expect("closed partitions must produce output")?;
    assert_eq!(polls.load(Ordering::SeqCst), 1, "sliced={sliced}");
    let expected = (0_i64..4)
        .map(|value| {
            vec![
                ScalarValue::Int32(Some((value / 2) as i32)),
                ScalarValue::Int64(Some(value)),
                ScalarValue::Utf8(Some("A".to_string())),
                ScalarValue::Int64(Some(1)),
                ScalarValue::Int64(Some(value % 2 + 1)),
            ]
        })
        .collect::<Vec<_>>();
    assert_eq!(typed_rows(&[output])?, expected, "sliced={sliced}");

    // A later input failure cannot suppress the already committed prefix
    // or turn the still-open match into a successful result.
    fail.store(true, Ordering::SeqCst);
    let error = poll_ready(&mut stream, &mut context)
        .expect("upstream failure must be returned")
        .expect_err("open tail must not emit before its input failure");
    assert!(error.to_string().contains("injected upstream failure"));
    assert!(matches!(
        stream.as_mut().poll_next(&mut context),
        Poll::Ready(None)
    ));
    Ok(())
}