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
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
// 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::core::{
    AfterMatchSkip, EmptyMatchesMode, MatchRecognizeDefinition,
    MatchRecognizeOutputContract, MatchRecognizeOutputSpec, Pattern, RowsPerMatch,
    Symbol, symbol_col_name,
};
use crate::planning::BoundMatchExpr;
use crate::planning::bound_expr_lowering::lower_bound_match_spec;
use crate::planning::expressions::test_support::bound_binary;
use crate::planning::logical::{
    LogicalMatchOutput, LogicalMatchProgramInput, LogicalSymbolInput, MatchRecognize,
};
use crate::planning::{
    BoundMatchAggregateCall, DefaultMatchRecognizePlanningContext, MatchMetadataFunction,
    MatchNavigation, MatchPatternFieldRef,
};
use datafusion::arrow::datatypes::DataType;
use datafusion::common::{Column, ScalarValue};
use datafusion::logical_expr::ExprSchemable;
use datafusion::logical_expr::{LogicalPlanBuilder, Operator, col, lit};

fn input() -> Result<LogicalPlan> {
    LogicalPlanBuilder::values(vec![
        vec![lit(1_i64)],
        vec![lit(2_i64)],
        vec![lit(3_i64)],
    ])?
    .project(vec![col("column1").alias("v")])?
    .build()
}
fn spec(predicate: BoundMatchExpr) -> BoundMatchSpec {
    BoundMatchSpec {
        partition_by: vec![],
        order_by: vec![],
        source_rows_per_match: RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
        after_match_skip: AfterMatchSkip::PastLastRow,
        pattern: Pattern::Symbol(Symbol::Named("A".to_owned())),
        symbols: vec!["A".to_owned()],
        definitions: vec![MatchRecognizeDefinition {
            symbol: "A".to_owned(),
            predicate,
        }],
        measures: vec![],
        output: MatchRecognizeOutputContract::Derived,
    }
}
fn compare(value: BoundMatchExpr) -> BoundMatchExpr {
    bound_binary(
        value,
        Operator::Gt,
        BoundMatchExpr::Literal(ScalarValue::Int64(Some(0))),
    )
}
fn field(symbol: &str) -> BoundMatchExpr {
    BoundMatchExpr::PatternField(MatchPatternFieldRef {
        symbol: symbol.to_owned(),
        column: Column::from_name("v"),
    })
}
fn requirements(predicate: BoundMatchExpr) -> Result<MatchRecognizeRequirements> {
    analyze_match_recognize_requirements(
        &mut DefaultMatchRecognizePlanningContext::new(),
        &input()?,
        &spec(predicate),
        MatchRecognizePlanningCapabilities::default(),
    )
}

#[test]
fn admission_uses_normalized_dependencies_and_not_syntax() -> Result<()> {
    let count_predicate = compare(BoundMatchExpr::Aggregate(BoundMatchAggregateCall {
        name: "count".into(),
        args: vec![],
        wildcard_symbol: Some("A".into()),
        distinct: false,
        filter: None,
        order_by: vec![],
        null_treatment: None,
    }));
    // Count bounds no longer participate in semantic admission.
    assert!(requirements(count_predicate.clone())?.requires_match_aware_defines());
    crate::planning::plan_match_recognize_from_source(
        &mut DefaultMatchRecognizePlanningContext::new(),
        input()?,
        spec(count_predicate),
    )?;
    for predicate in [
        BoundMatchExpr::InputExpr(col("v").gt(lit(0_i64))),
        compare(field("A")),
        compare(BoundMatchExpr::Navigation(MatchNavigation::Last {
            expr: Box::new(field("A")),
            offset: None,
        })),
        compare(BoundMatchExpr::Navigation(MatchNavigation::Prev {
            expr: Box::new(field("A")),
            offset: None,
            default: None,
        })),
        bound_binary(
            BoundMatchExpr::Metadata(MatchMetadataFunction::Classifier),
            Operator::Eq,
            BoundMatchExpr::Literal(ScalarValue::Utf8(Some("A".into()))),
        ),
    ] {
        assert!(
            !requirements(predicate.clone())?.requires_match_aware_defines(),
            "{predicate:?}"
        );
        crate::planning::plan_match_recognize_from_source(
            &mut DefaultMatchRecognizePlanningContext::new(),
            input()?,
            spec(predicate),
        )?;
    }
    Ok(())
}

#[test]
fn input_windows_in_define_require_scalar_role() -> Result<()> {
    use datafusion::logical_expr::WindowFunctionDefinition;
    use datafusion::logical_expr::expr::WindowFunction;
    use datafusion_functions_aggregate::sum::sum_udaf;

    let window =
        BoundMatchExpr::InputExpr(Expr::WindowFunction(Box::new(WindowFunction::new(
            WindowFunctionDefinition::AggregateUDF(sum_udaf()),
            vec![col("v")],
        ))));
    assert!(!requirements(compare(window.clone()))?.requires_match_aware_defines());

    let navigation = BoundMatchExpr::Navigation(MatchNavigation::Last {
        expr: Box::new(window),
        offset: None,
    });
    let error = requirements(compare(navigation)).expect_err(
        "a native input window inside match navigation must fail during source planning",
    );
    assert!(
        error
            .to_string()
            .contains("DEFINE InputExpr cannot contain window expressions"),
        "{error}"
    );
    Ok(())
}

#[test]
fn dotted_input_alias_remains_static_in_complete_planning() -> Result<()> {
    use datafusion::common::TableReference;

    // Construct the literal identifier directly: parsing "src.A" as a multipart
    // table reference would hide the difference this regression exercises.
    let input = LogicalPlanBuilder::from(input()?)
        .alias(TableReference::bare("src.A"))?
        .build()?;
    let request = spec(BoundMatchExpr::InputExpr(col("v").gt(lit(0_i64))));
    let requirements = analyze_match_recognize_requirements(
        &mut DefaultMatchRecognizePlanningContext::new(),
        &input,
        &request,
        MatchRecognizePlanningCapabilities::default(),
    )?;
    assert!(!requirements.requires_match_aware_defines());
    crate::planning::plan_match_recognize_from_source(
        &mut DefaultMatchRecognizePlanningContext::new(),
        input,
        request,
    )?;
    Ok(())
}

#[test]
fn candidate_metadata_requires_match_aware_evaluation_even_without_history() -> Result<()>
{
    for metadata in [
        MatchMetadataFunction::MatchNumber,
        MatchMetadataFunction::MatchSequenceNumber,
        MatchMetadataFunction::Excluded,
    ] {
        let excluded = metadata == MatchMetadataFunction::Excluded;
        let predicate = if excluded {
            BoundMatchExpr::Metadata(metadata)
        } else {
            compare(BoundMatchExpr::Metadata(metadata))
        };
        let mut request = spec(predicate);
        if excluded {
            // A symbol name does not determine exclusion: the same symbol is
            // used on both sides of the exclusion boundary in this pattern.
            request.pattern = Pattern::Alternation(vec![
                Pattern::Symbol(Symbol::Named("A".into())),
                Pattern::Exclude(Symbol::Named("A".into())),
            ]);
        }
        let requirement = analyze_match_recognize_requirements(
            &mut DefaultMatchRecognizePlanningContext::new(),
            &input()?,
            &request,
            MatchRecognizePlanningCapabilities::default(),
        )?;
        assert!(requirement.requires_match_aware_defines());
        assert_eq!(requirement.definitions()[0].symbol(), "A");
        crate::planning::plan_match_recognize_from_source(
            &mut DefaultMatchRecognizePlanningContext::new(),
            input()?,
            request,
        )?;
    }
    Ok(())
}

#[test]
fn deterministic_row_casts_need_no_match_aware_state() -> Result<()> {
    let ordinary = BoundMatchExpr::InputExpr(
        col("v")
            .cast_to(&DataType::Int8, input()?.schema())?
            .gt(lit(0_i64)),
    );
    assert!(!requirements(ordinary)?.requires_match_aware_defines());
    let candidate = compare(BoundMatchExpr::Cast {
        expr: Box::new(field("A")),
        data_type: DataType::Int8,
    });
    assert!(!requirements(candidate)?.requires_match_aware_defines());
    Ok(())
}

#[tokio::test]
async fn volatile_define_occurrences_are_absent_from_the_input_projection() -> Result<()>
{
    assert_volatile_input_occurrences(None).await
}

#[tokio::test]
async fn identical_volatile_boolean_operands_belong_to_the_matcher() -> Result<()> {
    for operator in [Operator::And, Operator::Or] {
        assert_volatile_input_occurrences(Some(operator)).await?;
    }
    Ok(())
}

#[tokio::test]
async fn custom_volatile_calls_stay_in_candidate_predicates() -> Result<()> {
    use crate::core::SymbolEvalMode;
    use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
    use datafusion::logical_expr::{Volatility, create_udf};
    use datafusion::prelude::SessionContext;
    use std::collections::BTreeSet;
    use std::sync::Arc;

    let udf = create_udf(
        "custom_volatile",
        vec![DataType::Int64],
        DataType::Boolean,
        Volatility::Volatile,
        Arc::new(|_| datafusion::common::exec_err!("custom volatile call ran eagerly")),
    );
    let call = BoundMatchExpr::InputExpr(udf.call(vec![col("v")]));
    let window_input = create_udf(
        "observe_window_input",
        vec![DataType::Int64],
        DataType::Int64,
        Volatility::Volatile,
        Arc::new(|args| Ok(args[0].clone())),
    );
    let previous = BoundMatchExpr::Navigation(MatchNavigation::Prev {
        expr: Box::new(BoundMatchExpr::InputExpr(window_input.call(vec![col("v")]))),
        offset: None,
        default: None,
    });
    let predicate = |count_symbol: &str| {
        let count = BoundMatchExpr::Aggregate(BoundMatchAggregateCall {
            name: "count".into(),
            args: vec![],
            wildcard_symbol: Some(count_symbol.into()),
            distinct: false,
            filter: None,
            order_by: vec![],
            null_treatment: None,
        });
        let comparison = |limit| {
            let threshold = BoundMatchExpr::Literal(ScalarValue::Int64(Some(limit)));
            bound_binary(
                call.clone(),
                Operator::Eq,
                bound_binary(count.clone(), Operator::LtEq, threshold),
            )
        };
        bound_binary(
            bound_binary(comparison(1), Operator::And, comparison(2)),
            Operator::And,
            bound_binary(previous.clone(), Operator::Eq, previous.clone()),
        )
    };

    // Same-symbol counts produce one Incremental predicate per symbol. Crossed
    // counts leave a local and Deferred expression for each Hybrid predicate.
    for (count_for_a, count_for_b, mode, expression_count) in [
        ("A", "B", SymbolEvalMode::Incremental, 1),
        ("B", "A", SymbolEvalMode::Hybrid, 2),
    ] {
        let input = input()?;
        let mut source = spec(predicate(count_for_a));
        source.pattern = Pattern::Alternation(vec![
            Pattern::Symbol(Symbol::Named("A".into())),
            Pattern::Symbol(Symbol::Named("B".into())),
        ]);
        source.symbols.push("B".into());
        source.definitions.push(MatchRecognizeDefinition {
            symbol: "B".into(),
            predicate: predicate(count_for_b),
        });
        let mut context = DefaultMatchRecognizePlanningContext::new();
        let source = BoundMatchSource::try_new(
            &mut context,
            input.clone(),
            source,
            MatchRecognizePlanningCapabilities::default(),
        )?;
        let lowered =
            lower_bound_match_spec(&mut context, &input, source.canonical_spec())?;
        let prepared = preparation::prepare_input_from_logical_spec(
            &mut context,
            lowered.input,
            &lowered.spec,
            &[],
            source.requirements(),
            false,
        )?;
        let window_names = prepared
            .prepared_exprs
            .iter()
            .filter(|item| matches!(item.expr, Expr::WindowFunction(_)))
            .map(|item| item.name.as_str())
            .collect::<BTreeSet<_>>();
        assert_eq!(window_names.len(), 4, "{mode:?}");
        let mut symbol_windows = BTreeSet::new();
        for plan in &prepared.symbol_plans {
            let mut forms =
                plan.predicate
                    .expressions()
                    .into_iter()
                    .flatten()
                    .map(|expr| {
                        expr.column_refs()
                            .into_iter()
                            .map(|column| column.name.as_str())
                            .filter(|name| window_names.contains(name))
                            .collect::<BTreeSet<_>>()
                    });
            let local = forms.next().expect("candidate has a local predicate");
            assert_eq!(local.len(), 2, "{}", plan.name);
            for deferred in forms {
                assert_eq!(local, deferred, "{}", plan.name);
            }
            assert!(symbol_windows.is_disjoint(&local), "{}", plan.name);
            symbol_windows.extend(local);
        }
        assert_eq!(symbol_windows, window_names, "{mode:?}");
        let prepared = preparation::process_defines(&mut context, prepared)?;
        assert_eq!(prepared.symbol_plans.len(), 2);
        for plan in &prepared.symbol_plans {
            assert_eq!(plan.predicate.mode(), mode, "{}", plan.name);
            let expressions = plan.predicate.expressions();
            assert_eq!(expressions.iter().flatten().count(), expression_count);
            for expr in expressions.into_iter().flatten() {
                let mut calls = 0;
                expr.apply(|node| {
                    if matches!(node, Expr::ScalarFunction(function) if function.func.as_ref() == &udf)
                    {
                        calls += 1;
                    }
                    Ok(TreeNodeRecursion::Continue)
                })?;
                assert_eq!(calls, 2, "{}: {expr}", plan.name);
            }
        }
        // Any eager candidate scalar call would fail the input projection.
        let batches = SessionContext::new()
            .execute_logical_plan(prepared.input)
            .await?
            .collect()
            .await?;
        assert_eq!(
            batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
            3
        );
    }
    Ok(())
}

async fn assert_volatile_input_occurrences(
    single_definition_operator: Option<Operator>,
) -> Result<()> {
    use datafusion::logical_expr::{Volatility, create_udf};
    use datafusion::prelude::{SessionConfig, SessionContext};
    use std::sync::Arc;

    let udf = create_udf(
        "observed_volatile",
        vec![DataType::Int64],
        DataType::Boolean,
        Volatility::Volatile,
        Arc::new(|_| datafusion::common::exec_err!("volatile DEFINE ran eagerly")),
    );
    for batch_size in [1, 2] {
        let predicate = BoundMatchExpr::InputExpr(udf.call(vec![col("v")]));
        let input = input()?;
        let mut source = spec(predicate.clone());
        if let Some(operator) = single_definition_operator {
            source.definitions[0].predicate =
                bound_binary(predicate.clone(), operator, predicate);
        } else {
            source.pattern = Pattern::Alternation(vec![
                Pattern::Symbol(Symbol::Named("A".into())),
                Pattern::Symbol(Symbol::Named("B".into())),
            ]);
            source.symbols.push("B".into());
            source.definitions.push(MatchRecognizeDefinition {
                symbol: "B".into(),
                predicate,
            });
        }
        let source = BoundMatchSource::try_new(
            &mut DefaultMatchRecognizePlanningContext::new(),
            input.clone(),
            source,
            MatchRecognizePlanningCapabilities::default(),
        )?;
        let mut context = DefaultMatchRecognizePlanningContext::new();
        let lowered =
            lower_bound_match_spec(&mut context, &input, source.canonical_spec())?;
        assert!(!source.requirements().requires_match_aware_defines());
        let prepared = preparation::prepare_input_from_logical_spec(
            &mut context,
            lowered.input,
            &lowered.spec,
            &[],
            source.requirements(),
            false,
        )?;
        let prepared = preparation::process_defines(&mut context, prepared)?;
        let output = SessionContext::new_with_config(
            SessionConfig::new().with_batch_size(batch_size),
        )
        .execute_logical_plan(prepared.input)
        .await?
        .collect()
        .await?;
        assert_eq!(
            output.iter().map(|batch| batch.num_rows()).sum::<usize>(),
            3
        );
        let mut occurrences = 0;
        for plan in prepared.symbol_plans {
            let crate::planning::phases::SymbolPlanPredicate::Demanded(expr) =
                plan.predicate
            else {
                panic!("volatile DEFINE must stay with the matcher");
            };
            use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
            expr.apply(|node| {
                if matches!(node, Expr::ScalarFunction(f) if f.func.as_ref() == &udf) {
                    occurrences += 1;
                }
                Ok(TreeNodeRecursion::Continue)
            })?;
        }
        assert_eq!(occurrences, 2);
    }
    Ok(())
}

fn static_program(expression: Expr) -> LogicalMatchProgramInput {
    LogicalMatchProgramInput {
        partition_by: vec![],
        order_by: vec![],
        after_skip: AfterMatchSkip::PastLastRow,
        pattern: Pattern::Symbol(Symbol::Named("A".into())),
        symbols: vec![LogicalSymbolInput::static_("A", expression)],
        match_aware: crate::planning::logical::ExecutableMatchProgramInput::new(
            vec![],
            vec![],
        ),
        output: LogicalMatchOutput::rows(
            RowsPerMatch::OneRow,
            MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
        ),
        symbol_relationships: Default::default(),
    }
}

#[test]
fn low_level_static_tag_cannot_smuggle_candidate_state_or_missing_bindings() -> Result<()>
{
    let child = LogicalPlanBuilder::from(input()?)
        .project(vec![lit(true).alias(symbol_col_name("A"))])?
        .build()?;
    for expression in [
        col("__mr_match_number").gt(lit(0_i64)),
        col("__mr_managed_agg_0").gt(lit(0_i64)),
        crate::functions::udf::match_number()
            .call(vec![])
            .gt(lit(0_u64)),
        crate::functions::udf::match_sequence_number()
            .call(vec![])
            .gt(lit(0_u64)),
        crate::functions::udf::classifier()
            .call(vec![])
            .eq(lit("A")),
        crate::functions::udf::excluded().call(vec![]),
    ] {
        let error = MatchRecognize::try_new(child.clone(), static_program(expression))
            .unwrap_err()
            .to_string();
        assert!(error.contains("match-aware DEFINE"), "{error}");
        assert!(error.contains("supplied as static input"), "{error}");
        assert!(
            error.contains("plan_match_recognize_from_source"),
            "{error}"
        );
        assert!(
            error.contains("match-aware 'LogicalSymbolInput'"),
            "{error}"
        );
    }
    assert!(MatchRecognize::try_new(input()?, static_program(lit(true))).is_err());
    assert!(MatchRecognize::try_new(child.clone(), static_program(lit(1_i64))).is_err());
    MatchRecognize::try_new(child, static_program(lit(true)))?;
    Ok(())
}

#[test]
fn low_level_static_tag_rejects_raw_navigation_windows() -> Result<()> {
    use crate::functions::udaf::{mr_next_udaf, mr_prev_udaf};
    use crate::functions::udwf::{
        mr_first_udwf, mr_last_udwf, mr_next_udwf, mr_prev_udwf,
    };
    use datafusion::functions_window::lead_lag::lag_udwf;
    use datafusion::logical_expr::{WindowFunctionDefinition, expr::WindowFunction};
    use datafusion_functions_aggregate::first_last::{first_value_udaf, last_value_udaf};

    let patterns = BTreeSet::from(["A".into()]);
    let generated = BTreeSet::new();
    let analysis = StaticAnalysis::new(&patterns, &generated);
    let child = LogicalPlanBuilder::from(input()?)
        .project(vec![lit(true).alias(symbol_col_name("A"))])?
        .build()?;

    for (fun, args) in [
        (
            WindowFunctionDefinition::WindowUDF(mr_first_udwf()),
            vec![col("v")],
        ),
        (
            WindowFunctionDefinition::WindowUDF(mr_last_udwf()),
            vec![col("v")],
        ),
        (
            WindowFunctionDefinition::WindowUDF(mr_prev_udwf()),
            vec![col("v"), lit(1_i64), lit(0_i64)],
        ),
        (
            WindowFunctionDefinition::WindowUDF(mr_next_udwf()),
            vec![col("v"), lit(1_i64), lit(0_i64)],
        ),
        (
            WindowFunctionDefinition::AggregateUDF(mr_prev_udaf()),
            vec![col("v"), lit(1_i64), lit(0_i64), lit(true), lit(true)],
        ),
        (
            WindowFunctionDefinition::AggregateUDF(mr_next_udaf()),
            vec![col("v"), lit(1_i64), lit(0_i64), lit(true), lit(true)],
        ),
    ] {
        let name = fun.name().to_owned();
        let window = WindowFunction::new(fun, args);
        assert!(is_match_scoped_window(&window, analysis), "{name}");
        let expression = Expr::WindowFunction(Box::new(window)).gt(lit(0_i64));
        assert!(!is_static(&expression, analysis), "{name}");
        let error = MatchRecognize::try_new(child.clone(), static_program(expression))
            .unwrap_err()
            .to_string();
        assert!(error.contains("match-aware DEFINE"), "{name}: {error}");
        assert!(
            error.contains("supplied as static input"),
            "{name}: {error}"
        );
    }

    for (fun, args) in [
        (
            WindowFunctionDefinition::WindowUDF(lag_udwf()),
            vec![col("v"), lit(1_i64), lit(0_i64)],
        ),
        (
            WindowFunctionDefinition::AggregateUDF(first_value_udaf()),
            vec![col("v")],
        ),
        (
            WindowFunctionDefinition::AggregateUDF(last_value_udaf()),
            vec![col("v")],
        ),
    ] {
        let name = fun.name().to_owned();
        let window = WindowFunction::new(fun, args);
        assert!(!is_match_scoped_window(&window, analysis), "{name}");
        let expr = Expr::WindowFunction(Box::new(window)).gt(lit(0_i64));
        assert!(is_static(&expr, analysis), "{name}");
        validate_static_predicate("A", &expr, &patterns)?;
    }
    Ok(())
}

#[test]
fn raw_metadata_placeholders_require_structured_source_but_same_named_udfs_are_static()
-> Result<()> {
    use datafusion::logical_expr::{ColumnarValue, Volatility, create_udf};
    use std::sync::Arc;
    struct ScalarContext {
        options: datafusion_common::config::ConfigOptions,
        function: Arc<datafusion::logical_expr::ScalarUDF>,
    }
    impl MatchRecognizePlanningContext for ScalarContext {
        fn options(&self) -> &datafusion_common::config::ConfigOptions {
            &self.options
        }
        fn scalar_udf(
            &self,
            name: &str,
        ) -> Option<Arc<datafusion::logical_expr::ScalarUDF>> {
            // A context may resolve an ordinary registry alias to a metadata
            // object, so validation must inspect the resolved implementation.
            (name == "resolved_scalar").then(|| Arc::clone(&self.function))
        }
    }
    use crate::functions::udf;
    for (name, placeholder) in [
        ("match_number", udf::match_number()),
        ("match_sequence_number", udf::match_sequence_number()),
        ("classifier", udf::classifier()),
        ("excluded", udf::excluded()),
    ] {
        let expression = placeholder.call(vec![]).is_not_null();
        let error = requirements(BoundMatchExpr::InputExpr(expression))
            .unwrap_err()
            .to_string();
        assert!(error.contains("use BoundMatchExpr::Metadata"), "{error}");
        let named = BoundMatchExpr::ScalarFunction {
            name: "resolved_scalar".into(),
            args: vec![],
        };
        let error = analyze_match_recognize_requirements(
            &mut ScalarContext {
                options: Default::default(),
                function: placeholder,
            },
            &input()?,
            &spec(named.clone()),
            MatchRecognizePlanningCapabilities::default(),
        )
        .unwrap_err()
        .to_string();
        assert!(error.contains("use BoundMatchExpr::Metadata"), "{error}");
        let custom = create_udf(
            name,
            vec![],
            DataType::Boolean,
            Volatility::Volatile,
            Arc::new(|_| Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))))),
        );
        let expression = custom.call(vec![]);
        let custom_requirements = analyze_match_recognize_requirements(
            &mut DefaultMatchRecognizePlanningContext::new(),
            &input()?,
            &spec(BoundMatchExpr::InputExpr(expression.clone())),
            MatchRecognizePlanningCapabilities::restricted(false, false),
        )?;
        assert!(!custom_requirements.requires_match_aware_defines());
        let custom_requirements = analyze_match_recognize_requirements(
            &mut ScalarContext {
                options: Default::default(),
                function: Arc::new(custom),
            },
            &input()?,
            &spec(named),
            MatchRecognizePlanningCapabilities::restricted(false, false),
        )?;
        assert!(!custom_requirements.requires_match_aware_defines());
        validate_static_predicate("A", &expression, &BTreeSet::from(["A".into()]))?;
    }
    Ok(())
}

#[test]
fn pure_count_metadata_comparison_retains_candidate_evaluation() -> Result<()> {
    let predicate = bound_binary(
        BoundMatchExpr::Aggregate(BoundMatchAggregateCall {
            name: "count".into(),
            args: vec![compare(BoundMatchExpr::Metadata(
                MatchMetadataFunction::MatchNumber,
            ))],
            wildcard_symbol: None,
            distinct: false,
            filter: None,
            order_by: vec![],
            null_treatment: None,
        }),
        Operator::GtEq,
        BoundMatchExpr::Literal(ScalarValue::Int64(Some(0))),
    );
    assert!(requirements(predicate.clone())?.requires_match_aware_defines());
    crate::planning::plan_match_recognize_from_source(
        &mut DefaultMatchRecognizePlanningContext::new(),
        input()?,
        spec(predicate),
    )?;
    Ok(())
}