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
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
// 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.

//! Optimized plan export safety, payload contracts, and extension graph round trips.

use super::*;

#[tokio::test]
async fn mixed_aggregates_roundtrip_ordinary_and_legacy_one_row_boundaries() -> Result<()>
{
    let ctx = context_with_input().await?;
    let sql = r#"
SELECT company, row_count, total_price
FROM t
MATCH_RECOGNIZE (
  PARTITION BY company
  ORDER BY ts
  MEASURES
    COUNT(*) AS row_count,
    SUM(A.price) AS total_price
  ONE ROW PER MATCH
  AFTER MATCH SKIP PAST LAST ROW
  PATTERN (A+)
  DEFINE A AS price > 0
)
ORDER BY company, row_count, total_price
"#;
    let direct = ctx.sql(sql).await?.logical_plan().clone();
    let ordinary = ctx
        .sql(&sql.replace("SUM(A.price)", "SUM(DISTINCT A.price)"))
        .await?
        .logical_plan()
        .clone();
    for (plan, native) in [(&direct, true), (&ordinary, false)] {
        let exported = to_substrait_plan_with_match_recognize(plan, &ctx.state())?;
        let payload = root_payload(&exported)?;
        assert!(payload.semantic_node);
        assert_eq!(payload.semantic_node_finalizes_one_row, native);
        assert_roundtrip_output(
            &ctx,
            plan.clone(),
            &[
                ("company", DataType::Utf8, true),
                ("row_count", DataType::Int64, false),
                ("total_price", DataType::Int64, true),
            ],
            &[vec!["acme".into(), 3_i64.into(), 36_i64.into()]],
        )
        .await?;
    }

    // The explicit one-row contract can request a representative source column as well
    // as stable summary slots. Recreate this boundary just as an older producer
    // did, and verify that a current importer can still execute its projection.
    let source = match_recognize_node(&ordinary)
        .unwrap()
        .bound_source()
        .unwrap();
    let legacy = 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 legacy = LogicalPlanBuilder::from(legacy)
        .project(vec![
            col("price").alias("representative_price"),
            col("__mr_count_summary_0").alias("row_count"),
            col("__mr_count_summary_1").alias("total_price"),
        ])?
        .build()?;
    let legacy_export = to_substrait_plan_with_match_recognize(&legacy, &ctx.state())?;
    assert!(root_payload(&legacy_export)?.semantic_node_finalizes_one_row);
    assert_roundtrip_output(
        &ctx,
        legacy,
        &[
            ("representative_price", DataType::Int64, true),
            ("row_count", DataType::Int64, false),
            ("total_price", DataType::Int64, true),
        ],
        &[vec![10_i64.into(), 3_i64.into(), 36_i64.into()]],
    )
    .await
}

#[tokio::test]
async fn pruned_native_one_row_node_roundtrips_without_summary_columns() -> Result<()> {
    let ctx = context_with_input().await?;
    let direct = sql_plan(
        &ctx,
        "SELECT company, row_count FROM t MATCH_RECOGNIZE (
        PARTITION BY company ORDER BY ts MEASURES COUNT(*) AS row_count
        ONE ROW PER MATCH PATTERN (A+) DEFINE A AS price>0)",
    )
    .await?;
    let node = match_recognize_node(&direct).expect("native logical node");
    let output = node
        .pruned_output_for_projection_exprs(&[col("company")])
        .expect("summary output should be pruned");
    let pruned = node.rebuild_with_output(output)?;
    assert!(pruned.program().selected_match_summaries().is_empty());
    let pruned = LogicalPlan::Extension(Extension {
        node: Arc::new(pruned),
    });
    let exported = to_substrait_plan_with_match_recognize(&pruned, &ctx.state())?;
    assert!(root_payload(&exported)?.semantic_node_finalizes_one_row);
    assert_roundtrip_output(
        &ctx,
        pruned,
        &[("company", DataType::Utf8, true)],
        &[vec!["acme".into()]],
    )
    .await
}

#[tokio::test]
async fn optimized_exports_preserve_rows() -> Result<()> {
    let ctx = export_context().await?;
    for (case, sql, columns, rows) in [
        (
            "partition filter",
            "SELECT k, n FROM export_input MATCH_RECOGNIZE (
            PARTITION BY k ORDER BY ts MEASURES COUNT(*) AS n
            PATTERN (A+) DEFINE A AS true) WHERE k = 1 ORDER BY k",
            vec![("k", DataType::Int64, true), ("n", DataType::Int64, false)],
            vec![vec![1_i64.into(), 3_i64.into()]],
        ),
        (
            "pruned DEFINE input",
            "SELECT k, n FROM export_input MATCH_RECOGNIZE (
            PARTITION BY k ORDER BY ts MEASURES COUNT(*) AS n
            PATTERN (A+) DEFINE A AS price > 12) ORDER BY k",
            vec![("k", DataType::Int64, true), ("n", DataType::Int64, false)],
            vec![vec![1_i64.into(), 2_i64.into()]],
        ),
        (
            "swapped passthrough",
            "WITH input AS (
            SELECT ts, a AS b, b AS a FROM alias_input)
            SELECT a, n FROM input MATCH_RECOGNIZE (
            PARTITION BY a ORDER BY ts MEASURES COUNT(*) AS n
            PATTERN (A+) DEFINE A AS true) ORDER BY a",
            vec![("a", DataType::Int64, true), ("n", DataType::Int64, false)],
            vec![
                vec![10_i64.into(), 1_i64.into()],
                vec![20_i64.into(), 2_i64.into()],
            ],
        ),
        (
            "retained second summary without source output",
            "SELECT total FROM export_input MATCH_RECOGNIZE (
            ORDER BY ts MEASURES COUNT(*) AS unused, SUM(A.price) AS total
            ONE ROW PER MATCH PATTERN (A+) DEFINE A AS true)",
            vec![("total", DataType::Int64, true)],
            vec![vec![63_i64.into()]],
        ),
    ] {
        let direct = sql_plan(&ctx, sql).await?;
        let optimized = ctx.state().optimize(&direct)?;
        if case == "pruned DEFINE input" {
            let node = match_recognize_node(&optimized).expect("optimized match node");
            assert!(
                node.input()
                    .schema()
                    .index_of_column(&Column::new(Some("export_input"), "price"))
                    .is_err()
            );
        } else if case == "retained second summary without source output" {
            let node = match_recognize_node(&optimized).expect("optimized match node");
            let output = node.program().output();
            assert!(output.spec().passthrough_input_indices().is_empty());
            let summaries = output.selected_match_summaries();
            assert_eq!(summaries.len(), 1);
            assert_eq!(summaries[0].output_id(), 1);
        }

        assert_roundtrip_output(&ctx, optimized, &columns, &rows).await?;
    }
    let baseline = sql_plan(&ctx, "SELECT k, n FROM export_input MATCH_RECOGNIZE (
        PARTITION BY k ORDER BY ts MEASURES COUNT(*) AS n PATTERN (A+) DEFINE A AS true) ORDER BY k").await?;
    let columns = [("k", DataType::Int64, true), ("n", DataType::Int64, false)];
    assert_output(
        &ctx,
        baseline.clone(),
        &columns,
        &[
            vec![1_i64.into(), 3_i64.into()],
            vec![2_i64.into(), 3_i64.into()],
        ],
    )
    .await?;
    let rewritten = baseline
        .transform_up(|plan| {
            if matches!(plan, LogicalPlan::TableScan(_)) {
                Ok(Transformed::yes(
                    LogicalPlanBuilder::from(plan)
                        .filter(col("export_input.k").eq(lit(2_i64)))?
                        .build()?,
                ))
            } else {
                Ok(Transformed::no(plan))
            }
        })?
        .data;
    assert_roundtrip_output(
        &ctx,
        rewritten,
        &columns,
        &[vec![2_i64.into(), 3_i64.into()]],
    )
    .await?;
    Ok(())
}

#[tokio::test]
async fn reordered_row_output_preserves_explicit_identity() -> Result<()> {
    let ctx = export_context().await?;
    let plan = sql_plan(
        &ctx,
        "SELECT * FROM export_input MATCH_RECOGNIZE (
        ORDER BY ts, k MEASURES MATCH_NUMBER() AS mn
        ALL ROWS PER MATCH PATTERN (A B) DEFINE A AS true, B AS true)",
    )
    .await?;
    let node = match_recognize_node(&plan).expect("row-stream node");
    let output = node.program().output();
    let spec = output.spec();
    for group in 0..3 {
        let mut passthrough = spec.passthrough_input_indices().to_vec();
        let mut metadata = spec.metadata_columns().to_vec();
        let mut classifiers = spec.classifier_bitset_symbols().to_vec();
        match group {
            0 => passthrough.swap(0, 1),
            1 => metadata.swap(0, 1),
            _ => classifiers.swap(0, 1),
        }
        let reordered = node.rebuild_with_output(LogicalMatchOutput::rows(
            output.rows_per_match().clone(),
            MatchRecognizeOutputSpec::with_validated_navigation_offsets(
                passthrough,
                metadata,
                classifiers,
                spec.navigation_offsets(),
            ),
        ))?;
        let reordered = LogicalPlan::Extension(Extension {
            node: Arc::new(reordered),
        });
        let expected = plan_rows(&ctx, reordered.clone()).await?;
        assert_eq!(
            roundtrip_rows(&ctx, &reordered).await?,
            expected,
            "group {group}"
        );
    }
    Ok(())
}

#[tokio::test]
async fn optimized_navigation_export_is_safe() -> Result<()> {
    let ctx = export_context().await?;
    let direct = sql_plan(&ctx, "SELECT k, ts, previous, running FROM export_input MATCH_RECOGNIZE (
        PARTITION BY k ORDER BY ts MEASURES PREV(price) AS previous, SUM(A.price) AS running
        ALL ROWS PER MATCH PATTERN (A+) DEFINE A AS true) ORDER BY k, ts").await?;
    let optimized = ctx.state().optimize(&direct)?;
    assert_roundtrip_output(
        &ctx,
        optimized,
        &[
            ("k", DataType::Int64, true),
            ("ts", DataType::Int64, true),
            ("previous", DataType::Int64, true),
            ("running", DataType::Int64, true),
        ],
        &[
            vec![
                1_i64.into(),
                1_i64.into(),
                datafusion::common::ScalarValue::Int64(None),
                10_i64.into(),
            ],
            vec![1_i64.into(), 2_i64.into(), 10_i64.into(), 30_i64.into()],
            vec![1_i64.into(), 3_i64.into(), 20_i64.into(), 45_i64.into()],
            vec![
                2_i64.into(),
                1_i64.into(),
                datafusion::common::ScalarValue::Int64(None),
                5_i64.into(),
            ],
            vec![2_i64.into(), 2_i64.into(), 5_i64.into(), 11_i64.into()],
            vec![2_i64.into(), 3_i64.into(), 6_i64.into(), 18_i64.into()],
        ],
    )
    .await
}

#[tokio::test]
async fn changed_input_export_is_safe() -> Result<()> {
    let ctx = export_context().await?;
    let direct = sql_plan(
        &ctx,
        "SELECT k, n, total FROM export_input MATCH_RECOGNIZE (
        PARTITION BY k ORDER BY ts MEASURES COUNT(*) AS n, SUM(A.price) AS total
        PATTERN (A+) DEFINE A AS price > 12) ORDER BY k",
    )
    .await?;
    let changed = rewrite_match_input(direct.clone(), |input| {
        // Keep the already computed __mr_symbol_a mask while changing values
        // consumed by SUM. Replanning DEFINE over these values changes matches.
        project_input_column(input, "price", col("export_input.price") + lit(100_i64))
    })?;

    let columns = [
        ("k", DataType::Int64, true),
        ("n", DataType::Int64, false),
        ("total", DataType::Int64, true),
    ];
    assert_output(
        &ctx,
        direct,
        &columns,
        &[vec![1_i64.into(), 2_i64.into(), 35_i64.into()]],
    )
    .await?;
    assert_output(
        &ctx,
        changed.clone(),
        &columns,
        &[vec![1_i64.into(), 2_i64.into(), 235_i64.into()]],
    )
    .await?;
    assert_export_rejected(
        &ctx,
        &changed,
        "rewritten input boundary containing prepared column '__mr_symbol_a'",
    );
    Ok(())
}

#[tokio::test]
async fn changed_static_masks_do_not_recompute_original_define() -> Result<()> {
    let ctx = export_context().await?;
    let direct = sql_plan(
        &ctx,
        "SELECT k, n FROM export_input MATCH_RECOGNIZE (
        PARTITION BY k ORDER BY ts MEASURES COUNT(*) AS n
        PATTERN (A+) DEFINE A AS price > 12) ORDER BY k",
    )
    .await?;

    let columns = [("k", DataType::Int64, true), ("n", DataType::Int64, false)];
    assert_output(
        &ctx,
        direct.clone(),
        &columns,
        &[vec![1_i64.into(), 2_i64.into()]],
    )
    .await?;
    let projected = rewrite_match_input(direct.clone(), |input| {
        project_input_column(input, "__mr_symbol_a", lit(true))
    })?;
    let merged =
        rewrite_prepared_projection(direct.clone(), "__mr_symbol_a", |_| Ok(lit(true)))?;
    let window = rewrite_match_input(direct, |input| {
        let windowed =
            replace_column_with_lag(input, "__mr_symbol_a", lit(true), lit(true))?;
        // IS TRUE restores the non-null mask contract after nullable LAG.
        LogicalPlanBuilder::from(windowed)
            .project(input.schema().columns().into_iter().map(|column| {
                if column.name == "__mr_symbol_a" {
                    Expr::IsTrue(Box::new(Expr::Column(column))).alias("__mr_symbol_a")
                } else {
                    Expr::Column(column)
                }
            }))?
            .build()
    })?;
    for (changed, optimize, rejection) in [
        (projected, false, "rewritten prepared column"),
        // Projection validation now reaches the missing original DEFINE input
        // before the final source-column recovery check.
        (merged, true, "No field named export_input.price"),
        (window, false, "rewritten prepared column"),
    ] {
        let changed = if optimize {
            ctx.state().optimize(&changed)?
        } else {
            changed
        };
        assert_output(
            &ctx,
            changed.clone(),
            &columns,
            &[
                vec![1_i64.into(), 3_i64.into()],
                vec![2_i64.into(), 3_i64.into()],
            ],
        )
        .await?;
        assert_export_rejected(&ctx, &changed, rejection);
    }
    Ok(())
}

#[tokio::test]
async fn prepared_navigation_boundaries_are_safe() -> Result<()> {
    let ctx = context_with_input().await?;
    for (predicate, fetch) in [
        ("price > PREV(price)", None),
        ("price < NEXT(price)", Some(2)),
    ] {
        let direct = sql_plan(
            &ctx,
            &format!(
                "SELECT n FROM t MATCH_RECOGNIZE (
            ORDER BY ts MEASURES COUNT(*) AS n
            PATTERN (A+) DEFINE A AS {predicate})"
            ),
        )
        .await?;
        let changed = rewrite_match_input(direct, |input| {
            // Filter/Limit is above the prepared LAG/LEAD and DEFINE mask.
            // Moving it below those calculations changes the accepted rows.
            let input = LogicalPlanBuilder::from(input.clone());
            if let Some(fetch) = fetch {
                input.limit(0, Some(fetch))?
            } else {
                input.filter(col("t.ts").gt(lit(1_i64)))?
            }
            .build()
        })?;

        assert_output(
            &ctx,
            changed.clone(),
            &[("n", DataType::Int64, false)],
            &[vec![2_i64.into()]],
        )
        .await?;
        assert_export_rejected(
            &ctx,
            &changed,
            "rewritten input boundary containing prepared column '__mr_expr_0'",
        );
    }
    Ok(())
}

#[tokio::test]
async fn all_rows_filtered_aggregate_windows_roundtrip_execution() -> Result<()> {
    let ctx = context_with_input().await?;
    let queries = [
        r#"
SELECT company, ts, cls, b_count, b_sum
FROM t
MATCH_RECOGNIZE (
  PARTITION BY company
  ORDER BY ts
  MEASURES
    CLASSIFIER() AS cls,
    COUNT(B.*) AS b_count,
    SUM(B.price) AS b_sum
  ALL ROWS PER MATCH
  AFTER MATCH SKIP PAST LAST ROW
  PATTERN (A B*)
  DEFINE
    A AS price = 10,
    B AS price > 10
)
ORDER BY company, ts
"#,
        r#"
SELECT company, ts, row_count
FROM t
MATCH_RECOGNIZE (
  PARTITION BY company
  ORDER BY ts
  MEASURES COUNT(*) AS row_count
  ALL ROWS PER MATCH SHOW EMPTY MATCHES
  AFTER MATCH SKIP TO NEXT ROW
  PATTERN (A*)
  DEFINE A AS price < 0
)
ORDER BY company, ts
"#,
    ];

    let cases = [
        (
            vec![
                ("company", DataType::Utf8, true),
                ("ts", DataType::Int64, true),
                ("cls", DataType::Utf8, true),
                ("b_count", DataType::Int64, false),
                ("b_sum", DataType::Int64, true),
            ],
            vec![
                vec![
                    "acme".into(),
                    1_i64.into(),
                    "A".into(),
                    0_i64.into(),
                    datafusion::common::ScalarValue::Int64(None),
                ],
                vec![
                    "acme".into(),
                    2_i64.into(),
                    "B".into(),
                    1_i64.into(),
                    12_i64.into(),
                ],
                vec![
                    "acme".into(),
                    3_i64.into(),
                    "B".into(),
                    2_i64.into(),
                    26_i64.into(),
                ],
            ],
        ),
        (
            vec![
                ("company", DataType::Utf8, true),
                ("ts", DataType::Int64, true),
                ("row_count", DataType::Int64, false),
            ],
            vec![
                vec!["acme".into(), 1_i64.into(), 0_i64.into()],
                vec!["acme".into(), 2_i64.into(), 0_i64.into()],
                vec!["acme".into(), 3_i64.into(), 0_i64.into()],
            ],
        ),
    ];
    assert_eq!(
        queries.len(),
        cases.len(),
        "every SQL case needs a literal oracle"
    );
    for (sql, (columns, rows)) in queries.into_iter().zip(cases) {
        assert_roundtrip_output(&ctx, sql_plan(&ctx, sql).await?, &columns, &rows)
            .await?;
    }
    Ok(())
}

#[tokio::test]
async fn export_required_features_follow_actual_metadata_usage() -> Result<()> {
    let ctx = context_with_input().await?;
    for (function, required) in [
        (None, None),
        (
            Some(payload::MetadataFunction::MatchSequenceNumber),
            Some(DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE),
        ),
        (
            Some(payload::MetadataFunction::Excluded),
            Some(DATAFUSION_EXCLUDED_FEATURE),
        ),
    ] {
        let mut source = base_payload();
        // Unused declarations must not leak into inferred export requirements.
        source.required_features.extend([
            DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE.into(),
            DATAFUSION_EXCLUDED_FEATURE.into(),
        ]);
        if let Some(function) = function {
            source.measures.push(payload::RowPatternMeasure {
                name: Some("extra".into()),
                expression: Some(metadata(function)),
            });
            let ty = if function == payload::MetadataFunction::Excluded {
                bool_type()
            } else {
                i64_type()
            };
            source.output_schema = Some(named_struct(vec![
                ("company", string_type()),
                ("last_price", i64_type()),
                ("extra", ty),
            ]));
        }
        let imported = from_substrait_plan_with_match_recognize(
            &ctx.state(),
            &plan_for_payload(source),
        )
        .await?;
        let exported = to_substrait_plan_with_match_recognize(&imported, &ctx.state())?;
        let actual = root_payload(&exported)?
            .required_features
            .into_iter()
            .filter(|name| {
                matches!(
                    name.as_str(),
                    DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE
                        | DATAFUSION_EXCLUDED_FEATURE
                )
            })
            .collect::<BTreeSet<_>>();
        assert_eq!(actual, required.into_iter().map(str::to_owned).collect());
    }
    Ok(())
}

#[tokio::test]
async fn export_payload_keeps_source_expressions_adapter_level() -> Result<()> {
    use payload::source_expression::Kind;
    let ctx = context_with_input().await?;
    let input = base_payload();
    let imported = from_substrait_plan_with_match_recognize(
        &ctx.state(),
        &plan_for_payload(input.clone()),
    )
    .await?;
    let exported = to_substrait_plan_with_match_recognize(&imported, &ctx.state())?;
    let payload = root_payload(&exported)?;
    let expr = |kind| payload::SourceExpression { kind: Some(kind) };
    let literal = |value| {
        expr(Kind::InputExpression(Expression {
            rex_type: Some(RexType::Literal(proto::expression::Literal {
                literal_type: Some(proto::expression::literal::LiteralType::I64(value)),
                nullable: false,
                type_variation_reference: 0,
            })),
        }))
    };
    let greater = |left, right| {
        expr(Kind::Binary(payload::BinaryExpr {
            left: Some(Box::new(left)),
            op: payload::BinaryOperator::Gt as i32,
            right: Some(Box::new(right)),
        }))
    };
    assert_eq!(payload.symbols, input.symbols);
    assert_eq!(payload.pattern, input.pattern);
    assert_eq!(payload.partition_expressions, input.partition_expressions);
    assert_eq!(payload.sorts, input.sorts);
    assert_eq!(payload.measures, input.measures);
    assert_eq!(
        payload.definitions,
        [
            payload::PatternDefinition {
                symbol: "A".into(),
                predicate: Some(greater(input_field(2), literal(0)))
            },
            payload::PatternDefinition {
                symbol: "B".into(),
                predicate: Some(greater(pattern_field("B", 2), literal(10)))
            },
        ]
    );
    Ok(())
}

#[tokio::test]
async fn extension_graph_exports_zero_root_parent_and_independent_children() -> Result<()>
{
    let ctx = context_with_input().await?;
    let root = from_substrait_plan_with_match_recognize(
        &ctx.state(),
        &plan_for_payload(base_payload()),
    )
    .await?;
    let right = from_substrait_plan_with_match_recognize(
        &ctx.state(),
        &plan_for_payload(base_payload()),
    )
    .await?;
    let matcher = LogicalPlan::Extension(Extension {
        node: Arc::new(match_recognize_node(&root).expect("matcher").clone()),
    });
    let cases = [
        (LogicalPlanBuilder::empty(false).build()?, "read", 0),
        (matcher, "matcher", 1),
        (
            LogicalPlanBuilder::from(root.clone())
                .project(vec![col("company")])?
                .build()?,
            "projection",
            1,
        ),
        (
            LogicalPlanBuilder::from(root).union(right)?.build()?,
            "union",
            2,
        ),
    ];
    for (plan, expected_root, count) in cases {
        let exported = to_substrait_plan_with_match_recognize(&plan, &ctx.state())?;
        let expected_urls = if count == 0 {
            vec![]
        } else {
            vec![MATCH_RECOGNIZE_TYPE_URL.to_owned()]
        };
        assert_eq!(exported.expected_type_urls, expected_urls);
        let root = root_rel(&exported);
        let kind = match root.rel_type.as_ref().unwrap() {
            RelType::Read(_) => "read",
            RelType::ExtensionSingle(_) => "matcher",
            RelType::Project(_) => "projection",
            RelType::Set(_) => "union",
            other => panic!("unexpected exported graph root: {other:?}"),
        };
        assert_eq!(kind, expected_root);
        let mut details = vec![];
        collect_match_recognize_details(root, &mut details);
        assert_eq!(details.len(), count);
    }
    Ok(())
}

#[tokio::test]
async fn programmatic_summary_preserves_raw_float_partition_identity() -> Result<()> {
    use crate::core::{MatchSummaryField, RepetitionQuantifier, symbol_col_name};
    use crate::planning::logical::LogicalSelectedMatchSummary;
    use datafusion::arrow::array::{BooleanArray, Float64Array};
    use datafusion::logical_expr::ExprSchemable;

    let ctx = context_with_input().await?;
    let values = [0_u64, 1 << 63, f64::NAN.to_bits(), f64::NAN.to_bits() + 1];
    ctx.register_batch(
        "raw_keys",
        RecordBatch::try_from_iter(vec![
            (
                "k",
                Arc::new(Float64Array::from_iter_values(values.map(f64::from_bits)))
                    as ArrayRef,
            ),
            ("v", Arc::new(Int64Array::from(vec![1; 4])) as ArrayRef),
            (
                &symbol_col_name("A"),
                Arc::new(BooleanArray::from(vec![true; 4])) as ArrayRef,
            ),
        ])?,
    )?;
    let input = ctx.table("raw_keys").await?.logical_plan().clone();
    let private = MatchRecognizeOutputSpec::new(vec![1], vec![], vec![]);
    let count = datafusion::functions_aggregate::count::count(col("v"));
    let (_, field) = count.to_field(private.build_df_schema(input.schema())?.as_ref())?;
    let Expr::AggregateFunction(count) = count else {
        unreachable!()
    };
    let node = MatchRecognize::try_new(
        input,
        LogicalMatchProgramInput {
            partition_by: vec![col("k")],
            order_by: vec![],
            after_skip: AfterMatchSkip::PastLastRow,
            // A merged partition would produce one match with a larger count.
            pattern: Pattern::Repetition(
                Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
                RepetitionQuantifier::OneOrMore,
            ),
            symbols: vec![LogicalSymbolInput::static_("A", lit(true))],
            match_aware: None,
            output: LogicalMatchOutput::selected_summaries(
                MatchRecognizeOutputSpec::new(vec![0], vec![], vec![]),
                private,
                vec![LogicalSelectedMatchSummary::new(
                    MatchSummaryField::new(0, field),
                    count,
                )],
            ),
            symbol_relationships: Default::default(),
        },
    )?;
    let batches = ctx
        .execute_logical_plan(LogicalPlan::Extension(Extension {
            node: Arc::new(node),
        }))
        .await?
        .collect()
        .await?;
    let mut actual = Vec::new();
    for batch in batches {
        let keys = batch
            .column(0)
            .as_any()
            .downcast_ref::<Float64Array>()
            .unwrap();
        let counts = batch
            .column(1)
            .as_any()
            .downcast_ref::<Int64Array>()
            .unwrap();
        for (key, count) in keys.iter().zip(counts.iter()) {
            actual.push((key.unwrap().to_bits(), count));
        }
    }
    actual.sort_unstable();
    let mut expected = values.map(|key| (key, Some(1)));
    expected.sort_unstable();
    assert_eq!(actual, expected);
    Ok(())
}

#[tokio::test]
async fn semantic_node_without_bound_source_is_rejected() -> Result<()> {
    let ctx = context_with_input().await?;
    let node = MatchRecognize::try_new(
        LogicalPlanBuilder::empty(false)
            .project(vec![lit(true).alias(crate::core::symbol_col_name("A"))])?
            .build()?,
        LogicalMatchProgramInput {
            partition_by: vec![],
            order_by: vec![],
            after_skip: AfterMatchSkip::PastLastRow,
            pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
            symbols: vec![LogicalSymbolInput::static_("A", lit(true))],
            match_aware: None,
            output: LogicalMatchOutput::rows(
                RowsPerMatch::OneRow,
                MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
            ),
            symbol_relationships: Default::default(),
        },
    )?;
    let stripped = LogicalPlan::Extension(Extension {
        node: Arc::new(node),
    });

    let err = to_substrait_plan_with_match_recognize(&stripped, &ctx.state())
        .expect_err("semantic MR without a bound source should not export");

    assert!(
        err.to_string()
            .contains("requires the logical node's retained BoundMatchSource"),
        "{err}"
    );
    Ok(())
}

#[tokio::test]
async fn sql_and_substrait_sources_lower_to_same_semantics() -> Result<()> {
    let ctx = context_with_input().await?;
    let sql = r#"
SELECT company, last_price
FROM t
MATCH_RECOGNIZE (
  PARTITION BY company ORDER BY ts
  MEASURES B.price AS last_price
  ONE ROW PER MATCH AFTER MATCH SKIP PAST LAST ROW
  PATTERN (A B+)
  DEFINE A AS price > 0, B AS B.price > 10
)"#;
    let sql_plan = ctx.sql(sql).await?.logical_plan().clone();
    let substrait_plan = from_substrait_plan_with_match_recognize(
        &ctx.state(),
        &plan_for_payload(base_payload()),
    )
    .await?;

    let sql_node = match_recognize_node(&sql_plan).expect("SQL plan contains matcher");
    let substrait_node =
        match_recognize_node(&substrait_plan).expect("Substrait plan contains matcher");
    assert_eq!(sql_node, substrait_node);
    Ok(())
}