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
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
// 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::substrait::schema::to_substrait_named_struct;

fn contract_plan(
    template: &Plan,
    payload: payload::MatchRecognizeRel,
    input_schema: NamedStruct,
) -> Plan {
    let mut plan = template.clone();
    plan.relations = plan_for_payload(payload).relations;
    let Some(plan_rel::RelType::Rel(root)) = &mut plan.relations[0].rel_type else {
        panic!("test_case root relation");
    };
    let Some(RelType::ExtensionSingle(extension)) = &mut root.rel_type else {
        panic!("test_case extension relation");
    };
    let Some(RelType::Read(read)) = &mut extension.input.as_mut().unwrap().rel_type
    else {
        panic!("test_case input relation");
    };
    read.base_schema = Some(input_schema);
    plan
}

#[tokio::test]
async fn prepared_window_output_uses_declared_ordinals() -> Result<()> {
    let ctx = context_with_input().await?;
    let direct = sql_plan(
        &ctx,
        "SELECT ts FROM t MATCH_RECOGNIZE (
            ORDER BY ts ALL ROWS PER MATCH PATTERN (A+)
            DEFINE A AS PREV(ts) < ts AND PREV(price) < price)",
    )
    .await?;
    let state = ctx.state();
    let exported = to_substrait_plan_with_match_recognize(&direct, &state)?;
    let mut semantic = root_payload(&exported)?;
    let [first, second] = semantic.prepared_output_fields.as_slice() else {
        panic!("expected two prepared window outputs");
    };
    assert_ne!(first.output_field, second.output_field);
    assert_ne!(first.expression, second.expression);

    let input_schema = named_struct(vec![
        ("company", string_type()),
        ("ts", i64_type()),
        ("price", i64_type()),
    ]);
    semantic.prepared_output_fields.reverse();
    let reordered = contract_plan(&exported, semantic.clone(), input_schema.clone());
    from_substrait_plan_with_match_recognize(&state, &reordered).await?;

    semantic.prepared_output_fields[1].expression =
        semantic.prepared_output_fields[0].expression.clone();
    let reused = contract_plan(&exported, semantic, input_schema);
    let error = from_substrait_plan_with_match_recognize(&state, &reused)
        .await
        .unwrap_err();
    assert!(
        error
            .to_string()
            .contains("does not identify one unambiguous retained field"),
        "{error}"
    );
    Ok(())
}

#[tokio::test]
async fn equal_volatile_prepared_windows_roundtrip_as_distinct_fields() -> Result<()> {
    let ctx = context_with_input().await?;
    let direct = sql_plan(
        &ctx,
        "SELECT ts FROM t MATCH_RECOGNIZE (
            ORDER BY ts ALL ROWS PER MATCH PATTERN (A+)
            DEFINE A AS PREV(RANDOM()) <> PREV(RANDOM()))",
    )
    .await?;
    let state = ctx.state();
    let exported = to_substrait_plan_with_match_recognize(&direct, &state)?;
    let semantic = root_payload(&exported)?;
    let [first, second] = semantic.prepared_output_fields.as_slice() else {
        panic!("expected separate prepared outputs for both volatile windows");
    };
    assert_ne!(first.output_field, second.output_field);
    assert_eq!(first.expression, second.expression);

    let input_schema = named_struct(vec![
        ("company", string_type()),
        ("ts", i64_type()),
        ("price", i64_type()),
    ]);
    let retained = contract_plan(&exported, semantic, input_schema);
    from_substrait_plan_with_match_recognize(&state, &retained).await?;
    from_substrait_plan_with_match_recognize(&state, &exported).await?;
    Ok(())
}

#[tokio::test]
async fn summary_output_fields_reject_omission_and_duplicate_identity() -> Result<()> {
    let ctx = context_with_input().await?;
    let direct = sql_plan(
        &ctx,
        "SELECT c1, c2 FROM t MATCH_RECOGNIZE (
            ORDER BY ts
            MEASURES COUNT(A.*) AS c1, COUNT(B.*) AS c2
            ONE ROW PER MATCH
            PATTERN (A+ B*)
            DEFINE A AS price < 14, B AS price >= 14)",
    )
    .await?;
    let state = ctx.state();
    let exported = to_substrait_plan_with_match_recognize(&direct, &state)?;
    let mut semantic = root_payload(&exported)?;
    let [first, second] = semantic.summary_output_fields.as_slice() else {
        panic!("expected two summary output identities");
    };
    assert_ne!(first.output_field, second.output_field);
    assert_ne!(first.filter, second.filter);

    let input_schema = named_struct(vec![
        ("company", string_type()),
        ("ts", i64_type()),
        ("price", i64_type()),
    ]);
    semantic.summary_output_fields.reverse();
    let reordered = contract_plan(&exported, semantic.clone(), input_schema.clone());
    from_substrait_plan_with_match_recognize(&state, &reordered).await?;

    let mut duplicated = semantic.clone();
    let first_summary = duplicated.summary_output_fields[0].clone();
    let second_output_field = duplicated.summary_output_fields[1].output_field;
    duplicated.summary_output_fields[1] = payload::SummaryOutputField {
        output_field: second_output_field,
        ..first_summary
    };
    let duplicated = contract_plan(&exported, duplicated, input_schema.clone());
    let error = from_substrait_plan_with_match_recognize(&state, &duplicated)
        .await
        .unwrap_err();
    assert!(
        error
            .to_string()
            .contains("does not identify one unambiguous retained field"),
        "{error}"
    );

    semantic.summary_output_fields.clear();
    let omitted = contract_plan(&exported, semantic, input_schema);
    let error = from_substrait_plan_with_match_recognize(&state, &omitted)
        .await
        .unwrap_err();
    assert!(
        error
            .to_string()
            .contains("does not identify one unambiguous retained field"),
        "{error}"
    );
    Ok(())
}

#[tokio::test]
async fn colliding_non_volatile_summaries_reject_excess_duplicate_identity() -> Result<()>
{
    let ctx = context_with_input().await?;
    let ordinary = sql_plan(
        &ctx,
        "SELECT s1, s2, s3 FROM t MATCH_RECOGNIZE (
            ORDER BY ts
            MEASURES
                SUM(CASE A.price WHEN 10 THEN 1 ELSE 0 END) AS s1,
                SUM(CASE WHEN A.price = 10 THEN 1 ELSE 0 END) AS s2,
                SUM(CASE WHEN B.price = 14 THEN 1 ELSE 0 END) AS s3
            ONE ROW PER MATCH
            PATTERN (A+ B*)
            DEFINE A AS price < 14, B AS price >= 14)",
    )
    .await?;
    let source = match_recognize_node(&ordinary)
        .expect("one-row matcher")
        .bound_source()
        .expect("bound source");
    let native = plan_match_recognize_native_one_row_node_from_source_with_capabilities(
        &mut crate::planning::DefaultMatchRecognizePlanningContext::new(),
        source.input().clone(),
        source.canonical_spec().as_spec().clone(),
        source.capabilities(),
    )?;
    let node = match_recognize_node(&native).expect("native one-row matcher");
    let summary_cols: Vec<String> = node
        .program()
        .selected_match_summaries()
        .iter()
        .map(|summary| summary.column_name())
        .collect();
    let direct = LogicalPlanBuilder::from(native)
        .project(vec![
            col(&summary_cols[0]).alias("s1"),
            col(&summary_cols[1]).alias("s2"),
            col(&summary_cols[2]).alias("s3"),
        ])?
        .build()?;
    let state = ctx.state();
    let exported = to_substrait_plan_with_match_recognize(&direct, &state)?;
    let semantic = root_payload(&exported)?;
    let [first, second, third] = semantic.summary_output_fields.as_slice() else {
        panic!("expected three summary output identities");
    };
    assert_eq!(first.args, second.args);
    assert_eq!(first.filter, second.filter);
    assert_ne!(first.filter, third.filter);

    let input_schema = named_struct(vec![
        ("company", string_type()),
        ("ts", i64_type()),
        ("price", i64_type()),
    ]);
    let valid = contract_plan(&exported, semantic.clone(), input_schema.clone());
    from_substrait_plan_with_match_recognize(&state, &valid).await?;

    let mut duplicated = semantic;
    let first_summary = duplicated.summary_output_fields[0].clone();
    let third_output_field = duplicated.summary_output_fields[2].output_field;
    duplicated.summary_output_fields[2] = payload::SummaryOutputField {
        output_field: third_output_field,
        ..first_summary
    };
    let duplicated = contract_plan(&exported, duplicated, input_schema);
    let error = from_substrait_plan_with_match_recognize(&state, &duplicated)
        .await
        .unwrap_err();
    assert!(
        error
            .to_string()
            .contains("does not identify one unambiguous retained field"),
        "{error}"
    );
    Ok(())
}

#[tokio::test]
async fn dictionary_struct_names_roundtrip_matcher_passthrough() -> Result<()> {
    let ctx = context_with_input().await?;
    // Keep the dictionary at the matcher boundary with a scalar root output.
    let plan = sql_plan(
        &ctx,
        r#"WITH dictionary_input AS (
            SELECT 1 AS id,
                arrow_cast(named_struct('label', CAST(2 AS BIGINT)),
                    'Dictionary(Int8, Struct("label": non-null Int64))') AS payload
        )
        SELECT COUNT(*) AS n
        FROM dictionary_input MATCH_RECOGNIZE (
            ORDER BY id ALL ROWS PER MATCH PATTERN (A) DEFINE A AS TRUE
        )
        WHERE payload IS NOT NULL"#,
    )
    .await?;
    assert_roundtrip_output(
        &ctx,
        plan,
        &[("n", DataType::Int64, false)],
        &[vec![1_i64.into()]],
    )
    .await
}

#[test]
fn dictionary_output_validates_both_child_nullabilities() -> Result<()> {
    use crate::substrait::schema::output_type_matches;
    use r#type::Nullability::{Nullable, Required, Unspecified};

    let dictionary =
        DataType::Dictionary(Box::new(DataType::Int64), Box::new(DataType::Int64));
    let child = |nullability| {
        Box::new(Type {
            kind: Some(r#type::Kind::I64(r#type::I64 {
                nullability,
                ..Default::default()
            })),
        })
    };
    let matches = |key, value| {
        let wire = Type {
            kind: Some(r#type::Kind::Map(Box::new(r#type::Map {
                key: Some(child(key)),
                value: Some(child(value)),
                nullability: Nullable as i32,
                type_variation_reference: DICTIONARY_MAP_TYPE_VARIATION_REF,
            }))),
        };
        output_type_matches(&dictionary, &dictionary, &wire)
    };
    for valid in [Nullable as i32, Required as i32] {
        assert!(matches(valid, valid)?);
        for invalid in [999, Unspecified as i32] {
            assert!(matches(invalid, valid).is_err());
            assert!(matches(valid, invalid).is_err());
        }
    }
    Ok(())
}

#[tokio::test]
async fn output_contract_checks_recursive_wire_properties() -> Result<()> {
    let structure = |name, nullable| {
        DataType::Struct(vec![Field::new(name, DataType::Int64, nullable)].into())
    };
    let list = |nullable| {
        DataType::List(Arc::new(Field::new(
            "custom_item",
            structure("leaf", true),
            nullable,
        )))
    };
    let map = |nullable| {
        DataType::Map(
            Arc::new(Field::new(
                "custom_entries",
                DataType::Struct(
                    vec![
                        Field::new("custom_key", DataType::Int64, false),
                        Field::new("custom_value", structure("leaf", false), nullable),
                    ]
                    .into(),
                ),
                false,
            )),
            true,
        )
    };
    for (case, actual_type, declared_type, admitted) in [
        (
            "struct nullability",
            structure("leaf", true),
            structure("leaf", false),
            false,
        ),
        (
            "struct name",
            structure("leaf", true),
            structure("other", true),
            false,
        ),
        ("list element nullability", list(false), list(true), false),
        ("map value nullability", map(false), map(true), false),
        (
            "decimal precision",
            DataType::Decimal128(12, 2),
            DataType::Decimal128(13, 2),
            false,
        ),
        (
            "decimal scale",
            DataType::Decimal128(12, 2),
            DataType::Decimal128(12, 3),
            false,
        ),
        (
            "timestamp precision",
            DataType::Timestamp(TimeUnit::Microsecond, None),
            DataType::Timestamp(TimeUnit::Nanosecond, None),
            false,
        ),
        (
            "timestamp timezone",
            DataType::Timestamp(TimeUnit::Nanosecond, Some("Europe/Paris".into())),
            DataType::Timestamp(TimeUnit::Nanosecond, None),
            false,
        ),
        ("string view", DataType::Utf8, DataType::Utf8View, true),
    ] {
        let builder =
            datafusion::execution::SessionStateBuilder::new().with_default_features();
        let ctx = new_match_recognize_context(builder)?;
        let input = Arc::new(Schema::new(vec![
            Field::new("ts", DataType::Int64, false),
            Field::new("value", actual_type.clone(), true),
        ]));
        ctx.register_batch("t", RecordBatch::new_empty(Arc::clone(&input)))?;
        for rows in ["ONE ROW PER MATCH", "ALL ROWS PER MATCH"] {
            let direct = sql_plan(
                &ctx,
                &format!(
                    "SELECT * FROM t MATCH_RECOGNIZE (
                ORDER BY ts MEASURES LAST(A.value) AS observed {rows}
                PATTERN (A+) DEFINE A AS true)"
                ),
            )
            .await?;
            let node = match_recognize_node(&direct).expect("test_case matcher");
            let state = ctx.state();
            let exported = to_substrait_plan_with_match_recognize(&direct, &state)?;
            let semantic = root_payload(&exported)?;
            for complete in [false, true] {
                let mut payload = semantic.clone();
                let actual_schema = if complete {
                    payload.semantic_node = false;
                    payload.semantic_node_finalizes_one_row = false;
                    payload.retained_passthrough_input_fields.clear();
                    payload.prepared_output_fields.clear();
                    payload.summary_output_fields.clear();
                    payload
                        .required_features
                        .retain(|feature| feature != DATAFUSION_SEMANTIC_ONE_ROW_FEATURE);
                    direct.schema()
                } else {
                    node.schema()
                };
                let mut producer = MatchRecognizeSubstraitProducer::new(&state);
                let input_schema = to_substrait_named_struct(
                    &mut producer,
                    &Arc::new(DFSchema::try_from(input.as_ref().clone())?),
                )?;
                payload.output_schema =
                    Some(to_substrait_named_struct(&mut producer, actual_schema)?);
                let valid =
                    contract_plan(&exported, payload.clone(), input_schema.clone());
                let imported =
                    from_substrait_plan_with_match_recognize(&state, &valid).await?;
                let batches = ctx.execute_logical_plan(imported).await?.collect().await?;
                assert!(batches.iter().all(|batch| batch.num_rows() == 0));

                let mut fields = actual_schema.fields().to_vec();
                let index = fields
                    .iter()
                    .position(|field| field.data_type() == &actual_type)
                    .expect("test_case value output");
                fields[index] = Arc::new(
                    fields[index]
                        .as_ref()
                        .clone()
                        .with_data_type(declared_type.clone()),
                );
                let declared = Arc::new(DFSchema::try_from(Schema::new(fields))?);
                payload.output_schema =
                    Some(to_substrait_named_struct(&mut producer, &declared)?);
                let changed = contract_plan(&exported, payload, input_schema);
                let result =
                    from_substrait_plan_with_match_recognize(&state, &changed).await;
                if admitted {
                    result?;
                } else {
                    let error = result.expect_err(case);
                    let diagnostic = error.to_string();
                    assert!(
                        diagnostic.contains("output schema mismatch")
                            || diagnostic.contains(
                                "does not identify one unambiguous retained field"
                            ),
                        "{case}, {rows}, complete={complete}: {error}"
                    );
                }
            }
        }
    }
    Ok(())
}