datafusion-match-recognize 0.55.0

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
871
872
873
// 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 crate::compat::{Metadata, MetadataExt};
use crate::core::{
    AbsoluteRow, AfterMatchSkip, MatchRecognizeOutputSpec, NavigationOffset, Pattern,
    RowsPerMatch, Symbol,
};
use crate::planning::logical::{
    ExecutableMatchProgramInput, LogicalMatchOutput, LogicalMatchProgramInput,
    LogicalSymbolInput, MatchRecognize,
};
use crate::planning::{MatchCompilerOptions, SymbolRelationships, compile_match_program};
use datafusion::arrow::array::{Array, ArrayRef, BooleanArray, Int64Array, StringArray};
use datafusion::arrow::datatypes::{DataType, FieldRef};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{Column, ScalarValue, TableReference};
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryConsumer, MemoryPool};
use datafusion::functions_aggregate::first_last::{first_value_udaf, last_value_udaf};
use datafusion::logical_expr::execution_props::ExecutionProps;
use datafusion::logical_expr::expr::{WindowFunction, WindowFunctionDefinition};
use datafusion::logical_expr::function::AccumulatorArgs;
use datafusion::logical_expr::{
    Accumulator, AggregateUDF, AggregateUDFImpl, EmptyRelation, LogicalPlan, Signature,
    Volatility, col, lit,
};
use datafusion::physical_expr::create_physical_expr;
use datafusion::physical_planner::DefaultPhysicalPlanner;
use datafusion::prelude::SessionContext;
use std::sync::LazyLock;

use crate::execution::matching::path::{PathNode, PathStep, Sym};
use crate::execution::storage::collection::BatchCollection;

use super::*;

fn compile_deferred_spec(
    logical_field: Field,
    predicate: Expr,
) -> Result<DeferredProgramSpec> {
    compile_deferred_symbols(
        logical_field,
        Pattern::Symbol(Symbol::Named("A".into())),
        vec![LogicalSymbolInput::deferred("A", predicate)],
    )
}

fn compile_deferred_symbols(
    logical_field: Field,
    pattern: Pattern,
    symbols: Vec<LogicalSymbolInput>,
) -> Result<DeferredProgramSpec> {
    let input_schema = Arc::new(DFSchema::try_from(Schema::new(vec![logical_field]))?);
    let input = LogicalPlan::EmptyRelation(EmptyRelation {
        produce_one_row: false,
        schema: Arc::clone(&input_schema),
    });
    let node = MatchRecognize::try_new(
        input,
        LogicalMatchProgramInput {
            partition_by: vec![],
            order_by: vec![],
            after_skip: AfterMatchSkip::PastLastRow,
            pattern,
            symbols,
            match_aware: ExecutableMatchProgramInput::new(vec![], vec![]),
            output: LogicalMatchOutput::rows(
                RowsPerMatch::OneRow,
                MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
            ),
            symbol_relationships: SymbolRelationships::default(),
        },
    )?;
    let routed = compile_match_program(
        node.program(),
        input_schema.as_ref(),
        MatchCompilerOptions::default(),
    )?;
    Ok(routed.deferred().expect("deferred program").clone())
}

fn eval_single_row(
    factory: &DeferredEvaluatorFactory,
    batch: RecordBatch,
) -> Result<bool> {
    let schema = batch.schema();
    let collection = BatchCollection::try_new(vec![batch], schema)?;
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(8 << 20));
    let reservation = MemoryConsumer::new("compiler-test").register(&pool);
    let mut history = factory.candidate_history(&reservation)?;
    let nodes = [PathNode {
        step: PathStep {
            row: AbsoluteRow::new(0),
            sym: Sym::from_index(1),
            excluded: false,
        },
        prev: None,
        depth: 0,
    }];
    history.begin(0, SymbolId::try_new(1, 2).unwrap(), 1)?;
    loop {
        if let Some(accepted) =
            history.advance(&collection, &nodes, 0, 1, &mut |_| Ok(()))?
        {
            return Ok(accepted);
        }
    }
}

#[derive(Debug)]
struct PropagateNullabilityAccumulator(ScalarValue);

impl Accumulator for PropagateNullabilityAccumulator {
    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
        let input = &values[0];
        if !input.is_empty() {
            self.0 = ScalarValue::try_from_array(input, input.len() - 1)?;
        }
        Ok(())
    }

    fn evaluate(&mut self) -> Result<ScalarValue> {
        Ok(self.0.clone())
    }

    fn size(&self) -> usize {
        size_of::<Self>()
    }

    fn state(&mut self) -> Result<Vec<ScalarValue>> {
        Ok(vec![self.0.clone()])
    }

    fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
        self.update_batch(states)
    }
}

#[derive(Debug, PartialEq, Eq, Hash)]
struct PropagateNullabilityAgg;

impl AggregateUDFImpl for PropagateNullabilityAgg {
    fn name(&self) -> &str {
        "propagate_nullability"
    }

    fn signature(&self) -> &Signature {
        static SIGNATURE: LazyLock<Signature> =
            LazyLock::new(|| Signature::any(1, Volatility::Immutable));
        &SIGNATURE
    }

    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
        Ok(arg_types[0].clone())
    }

    fn return_field(&self, arg_fields: &[FieldRef]) -> Result<FieldRef> {
        Ok(Arc::new(
            Field::new(
                self.name(),
                arg_fields[0].data_type().clone(),
                arg_fields[0].is_nullable(),
            )
            .with_metadata(arg_fields[0].metadata().clone()),
        ))
    }

    fn accumulator(&self, acc_args: AccumulatorArgs<'_>) -> Result<Box<dyn Accumulator>> {
        Ok(Box::new(PropagateNullabilityAccumulator(
            ScalarValue::try_from(acc_args.return_field.data_type())?,
        )))
    }
}

#[test]
fn plan_operation_allows_physical_metadata_preservation_on_edge_aggregates() -> Result<()>
{
    let planner = DefaultPhysicalPlanner::default();
    let state = SessionContext::new().state();
    let planning_ctx = PhysicalPlanningContext::default();
    let symbols = [SymbolId::try_new(1, 2).unwrap()];
    let symbol_names = [None, Some("A".to_owned())];
    let physical_schema = Arc::new(Schema::new(vec![
        Field::new("value", DataType::Int64, true)
            .with_metadata(Metadata::new().with("source", "physical")),
    ]));

    for udaf in [first_value_udaf(), last_value_udaf()] {
        let predicate = Expr::WindowFunction(Box::new(WindowFunction::new(
            WindowFunctionDefinition::AggregateUDF(udaf),
            vec![col("value")],
        )))
        .eq(lit(42_i64));
        let spec =
            compile_deferred_spec(Field::new("value", DataType::Int64, true), predicate)?;
        let factory = DeferredEvaluatorFactory::try_from_spec(
            &spec,
            &planner,
            &state,
            &planning_ctx,
            &physical_schema,
            &symbols,
            &symbol_names,
        )?;
        let batch = RecordBatch::try_new(
            Arc::clone(&physical_schema),
            vec![Arc::new(Int64Array::from(vec![Some(42)]))],
        )?;
        assert!(eval_single_row(&factory, batch)?);
    }
    Ok(())
}

#[test]
fn plan_operation_allows_widened_nullability_and_rejects_narrowing() -> Result<()> {
    let planner = DefaultPhysicalPlanner::default();
    let state = SessionContext::new().state();
    let planning_ctx = PhysicalPlanningContext::default();
    let symbols = [SymbolId::try_new(1, 2).unwrap()];
    let symbol_names = [None, Some("A".to_owned())];
    let udaf = Arc::new(AggregateUDF::new_from_impl(PropagateNullabilityAgg));
    let predicate = Expr::WindowFunction(Box::new(WindowFunction::new(
        WindowFunctionDefinition::AggregateUDF(udaf),
        vec![col("value")],
    )))
    .is_null();

    // Conservative nullability widening (non-nullable logical -> nullable physical)
    // succeeds and builds a nullable predicate batch that accepts NULL results.
    let widened_spec = compile_deferred_spec(
        Field::new("value", DataType::Int64, false),
        predicate.clone(),
    )?;
    assert!(!widened_spec.operations()[0].result_field().is_nullable());
    let widened_physical_schema = Arc::new(Schema::new(vec![
        Field::new("value", DataType::Int64, true)
            .with_metadata(Metadata::new().with("widened", "true")),
    ]));
    let factory = DeferredEvaluatorFactory::try_from_spec(
        &widened_spec,
        &planner,
        &state,
        &planning_ctx,
        &widened_physical_schema,
        &symbols,
        &symbol_names,
    )?;
    let null_batch = RecordBatch::try_new(
        Arc::clone(&widened_physical_schema),
        vec![Arc::new(Int64Array::from(vec![None]))],
    )?;
    assert!(eval_single_row(&factory, null_batch)?);

    // Unsafe nullability narrowing (nullable logical -> non-nullable physical)
    // must still be rejected.
    let narrowed_spec =
        compile_deferred_spec(Field::new("value", DataType::Int64, true), predicate)?;
    assert!(narrowed_spec.operations()[0].result_field().is_nullable());
    let narrowed_physical_schema = Arc::new(Schema::new(vec![Field::new(
        "value",
        DataType::Int64,
        false,
    )]));
    let err = DeferredEvaluatorFactory::try_from_spec(
        &narrowed_spec,
        &planner,
        &state,
        &planning_ctx,
        &narrowed_physical_schema,
        &symbols,
        &symbol_names,
    )
    .expect_err("narrowing operation result nullability must fail");
    assert!(
        err.to_string()
            .contains("Deferred operation 0 lowered to field"),
        "{err}"
    );
    Ok(())
}

#[test]
fn qualified_duplicate_columns_rebase_by_position() -> Result<()> {
    let field = Arc::new(Field::new("value", DataType::Int64, true));
    let logical_schema = DFSchema::new_with_metadata(
        ["left", "right"]
            .into_iter()
            .map(|table| (Some(TableReference::bare(table)), Arc::clone(&field)))
            .collect(),
        Metadata::new(),
    )?;
    let expression = Expr::Column(Column::new(Some("left"), "value"))
        .lt(Expr::Column(Column::new(Some("right"), "value")));
    let physical = create_physical_expr(
        &expression,
        &logical_schema,
        &ExecutionProps::new(),
        &PhysicalPlanningContext::default(),
    )?;
    let target_schema = Arc::new(Schema::new(vec![Arc::clone(&field), field]));
    let rebased = rebase_physical_expr(physical, &target_schema, &[Some(1), Some(0)])?;
    let batch = RecordBatch::try_new(
        target_schema,
        vec![
            Arc::new(Int64Array::from(vec![Some(20), Some(5), None])),
            Arc::new(Int64Array::from(vec![Some(10), Some(10), Some(10)])),
        ],
    )?;
    let result = rebased.evaluate(&batch)?.into_array(batch.num_rows())?;
    assert_eq!(
        result.as_any().downcast_ref::<BooleanArray>().unwrap(),
        &BooleanArray::from(vec![Some(true), Some(false), None])
    );
    Ok(())
}

#[test]
fn plan_history_rejects_missing_and_mismatched_physical_inputs() -> Result<()> {
    let symbols = [SymbolId::try_new(1, 2).unwrap()];
    let predicate = Expr::WindowFunction(Box::new(WindowFunction::new(
        WindowFunctionDefinition::AggregateUDF(first_value_udaf()),
        vec![col("value")],
    )))
    .is_not_null();
    let spec =
        compile_deferred_spec(Field::new("value", DataType::Int64, true), predicate)?;
    // A checked logical program still needs to verify its physical child:
    // missing, renamed, or differently typed input fields cannot be rebound.
    for (schema, expected) in [
        (Schema::empty(), "outside physical input schema"),
        (
            Schema::new(vec![Field::new("renamed", DataType::Int64, true)]),
            "deferred history field value",
        ),
        (
            Schema::new(vec![Field::new("value", DataType::Int32, true)]),
            "deferred history field value",
        ),
    ] {
        let error = plan_history(&spec, &Arc::new(schema), &symbols)
            .expect_err("physical history fields must match their logical owners");
        assert!(error.to_string().contains(expected), "{error}");
    }
    Ok(())
}

#[test]
fn scalar_wrapped_aggregate_inputs_use_physical_nullability() -> Result<()> {
    let planner = DefaultPhysicalPlanner::default();
    let state = SessionContext::new().state();
    let planning_ctx = PhysicalPlanningContext::default();
    let propagate = Arc::new(AggregateUDF::new_from_impl(PropagateNullabilityAgg));
    #[allow(clippy::single_element_loop)]
    for (ty, argument, values) in [
        (
            DataType::Int64,
            datafusion::functions::core::coalesce()
                .call(vec![col("value"), col("value")]),
            Arc::new(Int64Array::from(vec![None])) as ArrayRef,
        ),
        // Disabled on branch-55 (DataFusion 55.3): LowerFunc does not implement
        // return_field_from_args until DataFusion 56, so its logical return
        // field is always nullable.
        /*
        (
            DataType::Utf8,
            datafusion::functions::string::lower().call(vec![col("value")]),
            Arc::new(StringArray::from(vec![None::<&str>])) as ArrayRef,
        ),
        */
    ] {
        let predicate = Expr::WindowFunction(Box::new(WindowFunction::new(
            WindowFunctionDefinition::AggregateUDF(Arc::clone(&propagate)),
            vec![argument],
        )))
        .is_null();
        let spec =
            compile_deferred_spec(Field::new("value", ty.clone(), false), predicate)?;
        assert!(!spec.operations()[0].result_field().is_nullable());
        let physical_schema = Arc::new(Schema::new(vec![Field::new("value", ty, true)]));
        let factory = DeferredEvaluatorFactory::try_from_spec(
            &spec,
            &planner,
            &state,
            &planning_ctx,
            &physical_schema,
            &[SymbolId::try_new(1, 2).unwrap()],
            &[None, Some("A".into())],
        )?;
        assert!(
            factory.program.operations[0]
                .planned
                .lowered
                .aggregate
                .field()
                .is_nullable()
        );
        assert!(eval_single_row(
            &factory,
            RecordBatch::try_new(physical_schema, vec![values])?
        )?);
    }
    Ok(())
}

#[test]
fn array_agg_lower_ignore_nulls_uses_widened_physical_field() -> Result<()> {
    use datafusion::logical_expr::expr::NullTreatment;
    let mut window = WindowFunction::new(
        WindowFunctionDefinition::AggregateUDF(
            datafusion::functions_aggregate::array_agg::array_agg_udaf(),
        ),
        vec![datafusion::functions::string::lower().call(vec![col("s")])],
    );
    window.params.null_treatment = Some(NullTreatment::IgnoreNulls);
    // IGNORE NULLS must not be optimized away using the logical non-nullability.
    let spec = compile_deferred_spec(
        Field::new("s", DataType::Utf8, false),
        Expr::WindowFunction(Box::new(window)).is_not_null(),
    )?;
    let physical_schema =
        Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, true)]));
    let factory = DeferredEvaluatorFactory::try_from_spec(
        &spec,
        &DefaultPhysicalPlanner::default(),
        &SessionContext::new().state(),
        &PhysicalPlanningContext::default(),
        &physical_schema,
        &[SymbolId::try_new(1, 2).unwrap()],
        &[None, Some("A".into())],
    )?;
    let argument = &factory.program.operations[0].planned.input_exprs[0];
    assert!(
        argument
            .return_field(&factory.program.history.schema)?
            .is_nullable()
    );
    let batch = RecordBatch::try_new(
        physical_schema,
        vec![Arc::new(StringArray::from(vec![None, Some("ABC")]))],
    )?;
    let operation = &factory.program.operations[0].planned;
    let mut accumulator = operation.lowered.aggregate.create_accumulator()?;
    let inputs = operation
        .input_exprs
        .iter()
        .map(|expr| expr.evaluate(&batch)?.into_array(batch.num_rows()))
        .collect::<Result<Vec<_>>>()?;
    accumulator.update_batch(&inputs)?;
    let ScalarValue::List(result) = accumulator.evaluate()? else {
        panic!("ARRAY_AGG must produce a list");
    };
    assert_eq!(
        result
            .values()
            .as_any()
            .downcast_ref::<StringArray>()
            .unwrap(),
        &StringArray::from(vec!["abc"])
    );
    Ok(())
}

#[test]
fn coalesce_preserves_physical_field_metadata_through_aggregate_lowering() -> Result<()> {
    let physical_metadata = Metadata::new().with("source", "physical");
    let physical_schema = Arc::new(Schema::new_with_metadata(
        vec![
            Field::new("value", DataType::Int64, true)
                .with_metadata(physical_metadata.clone()),
        ],
        Metadata::new().with("schema_source", "physical"),
    ));
    let argument =
        datafusion::functions::core::coalesce().call(vec![col("value"), col("value")]);
    let predicate = Expr::WindowFunction(Box::new(WindowFunction::new(
        WindowFunctionDefinition::AggregateUDF(first_value_udaf()),
        vec![argument],
    )))
    .eq(lit(42_i64));
    let spec = compile_deferred_spec(
        Field::new("value", DataType::Int64, true)
            .with_metadata(Metadata::new().with("source", "logical")),
        predicate,
    )?;
    let factory = DeferredEvaluatorFactory::try_from_spec(
        &spec,
        &DefaultPhysicalPlanner::default(),
        &SessionContext::new().state(),
        &PhysicalPlanningContext::default(),
        &physical_schema,
        &[SymbolId::try_new(1, 2).unwrap()],
        &[None, Some("A".into())],
    )?;
    let operation = &factory.program.operations[0].planned;
    assert_eq!(
        operation.input_exprs[0]
            .return_field(&factory.program.history.schema)?
            .metadata(),
        &physical_metadata
    );
    assert_eq!(
        operation.lowered.aggregate.field().metadata(),
        &physical_metadata
    );
    assert_eq!(
        factory.program.predicates[1]
            .as_ref()
            .unwrap()
            .predicate_schema
            .field(0)
            .metadata(),
        &physical_metadata
    );
    assert_eq!(
        physical_backed_schema(spec.history_schema(), &factory.program.history.schema)?
            .metadata(),
        physical_schema.metadata()
    );
    assert!(eval_single_row(
        &factory,
        RecordBatch::try_new(
            physical_schema,
            vec![Arc::new(Int64Array::from(vec![42]))]
        )?
    )?);
    Ok(())
}

#[test]
fn checking_a_does_not_evaluate_unreached_b_operations() -> Result<()> {
    use crate::core::{RepetitionQuantifier, classifier_bits_col_name};
    let array_agg = |argument| {
        let mut window = WindowFunction::new(
            WindowFunctionDefinition::AggregateUDF(
                datafusion::functions_aggregate::array_agg::array_agg_udaf(),
            ),
            vec![argument],
        );
        window.params.filter = Some(Box::new(col(classifier_bits_col_name("A"))));
        Expr::WindowFunction(Box::new(window))
    };
    for accept_a in [true, false] {
        let a = array_agg(col("x"));
        let b = Pattern::Symbol(Symbol::Named("B".into()));
        let pattern = Pattern::Concat(vec![
            Pattern::Symbol(Symbol::Named("A".into())),
            if accept_a {
                Pattern::Repetition(Box::new(b), RepetitionQuantifier::AtMostOne)
            } else {
                b
            },
        ]);
        let spec = compile_deferred_symbols(
            Field::new("x", DataType::Int64, false),
            pattern,
            vec![
                LogicalSymbolInput::deferred(
                    "A",
                    if accept_a {
                        a.is_not_null()
                    } else {
                        a.is_null()
                    },
                ),
                LogicalSymbolInput::deferred(
                    "B",
                    array_agg(lit(1_i64) / col("x")).is_not_null(),
                ),
            ],
        )?;
        let physical_schema =
            Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, false)]));
        let factory = DeferredEvaluatorFactory::try_from_spec(
            &spec,
            &DefaultPhysicalPlanner::default(),
            &SessionContext::new().state(),
            &PhysicalPlanningContext::default(),
            &physical_schema,
            &[
                SymbolId::try_new(1, 3).unwrap(),
                SymbolId::try_new(2, 3).unwrap(),
            ],
            &[None, Some("A".into()), Some("B".into())],
        )?;
        assert_eq!(
            factory.program.predicates[1]
                .as_ref()
                .unwrap()
                .operation_indices,
            vec![0]
        );
        assert_eq!(
            factory.program.predicates[2]
                .as_ref()
                .unwrap()
                .operation_indices,
            vec![1]
        );
        let values = if accept_a { vec![0] } else { vec![0, 2] };
        assert_eq!(
            eval_single_row(
                &factory,
                RecordBatch::try_new(
                    physical_schema,
                    vec![Arc::new(Int64Array::from(values))]
                )?
            )?,
            accept_a
        );
    }
    Ok(())
}

#[cfg(feature = "sql")]
#[tokio::test]
async fn sql_unreached_deferred_symbol_cannot_raise_divide_by_zero() -> Result<()> {
    let ctx = crate::new_match_recognize_context(
        datafusion::execution::SessionStateBuilder::new().with_default_features(),
    )?;
    for (pattern, values, a_test, expected_rows) in [
        ("A B?", "(0, 0)", "IS NOT NULL", 1),
        ("A B", "(0, 0), (1, 2)", "IS NULL", 0),
    ] {
        let sql = format!(
            "WITH t(ord, x) AS (VALUES {values}) SELECT ord FROM t
            MATCH_RECOGNIZE (
                ORDER BY ord
                ALL ROWS PER MATCH
                PATTERN ({pattern})
                DEFINE A AS ARRAY_AGG(A.x) {a_test},
                       B AS ARRAY_AGG(1 / A.x) IS NOT NULL
            )"
        );
        let batches = ctx.sql(&sql).await?.collect().await?;
        assert_eq!(
            batches.iter().map(RecordBatch::num_rows).sum::<usize>(),
            expected_rows,
            "{sql}"
        );
    }
    Ok(())
}

#[test]
fn shared_operations_keep_symbol_local_accumulators_and_replay() -> Result<()> {
    let sum = Expr::WindowFunction(Box::new(WindowFunction::new(
        WindowFunctionDefinition::AggregateUDF(
            datafusion::functions_aggregate::sum::sum_udaf(),
        ),
        vec![col("x")],
    )));
    let count = Expr::WindowFunction(Box::new(WindowFunction::new(
        WindowFunctionDefinition::AggregateUDF(
            datafusion::functions_aggregate::count::count_udaf(),
        ),
        vec![col("x")],
    )));
    let sequence = col(MatchMetadataColumn::MatchSequenceNumber.as_ref());
    let pattern = Pattern::Concat(
        ["A", "B", "A"]
            .into_iter()
            .map(|name| Pattern::Symbol(Symbol::Named(name.into())))
            .collect(),
    );
    let spec = compile_deferred_symbols(
        Field::new("x", DataType::Int64, false),
        pattern,
        vec![
            LogicalSymbolInput::deferred("A", sum.clone().eq(sequence.clone())),
            LogicalSymbolInput::deferred(
                "B",
                sum.eq(sequence.clone()).and(count.eq(sequence)),
            ),
        ],
    )?;
    let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, false)]));
    let symbols = [
        SymbolId::try_new(1, 3).unwrap(),
        SymbolId::try_new(2, 3).unwrap(),
    ];
    let mut factory = DeferredEvaluatorFactory::try_from_spec(
        &spec,
        &DefaultPhysicalPlanner::default(),
        &SessionContext::new().state(),
        &PhysicalPlanningContext::default(),
        &schema,
        &symbols,
        &[None, Some("A".into()), Some("B".into())],
    )?;
    assert_eq!(spec.operations().len(), 2);
    assert_eq!(
        spec.predicates()[0].as_ref().unwrap().operation_indices(),
        &[0]
    );
    assert_eq!(
        spec.predicates()[1].as_ref().unwrap().operation_indices(),
        &[0, 1]
    );
    let collection = BatchCollection::try_new(
        vec![RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(Int64Array::from(vec![1, 1, 1]))],
        )?],
        schema,
    )?;
    let nodes = [1, 2, 1, 1]
        .into_iter()
        .enumerate()
        .map(|(index, symbol)| PathNode {
            step: PathStep {
                row: AbsoluteRow::new(index.min(2) as u64),
                sym: Sym::from_index(symbol),
                excluded: false,
            },
            prev: match index {
                0 => None,
                1 => Some(0),
                _ => Some(1),
            },
            depth: index.min(2) as u32,
        })
        .collect::<Vec<_>>();
    // Exercise both deterministic reconstruction and the saved-input replay
    // used for volatile operations, including a fork after the B prefix.
    for save_inputs in [false, true] {
        for predicate in Arc::get_mut(&mut factory.program)
            .unwrap()
            .predicates
            .iter_mut()
            .flatten()
        {
            predicate.save_history_inputs = save_inputs;
        }
        let memory = crate::execution::common::memory::new_unbounded_state_memory();
        let mut history = factory.candidate_history(&memory)?;
        for (node, symbol) in [
            (0, symbols[0]),
            (1, symbols[1]),
            (2, symbols[0]),
            (3, symbols[0]),
        ] {
            history.begin(node, symbol, 1)?;
            let accepted = loop {
                if let Some(accepted) =
                    history.advance(&collection, &nodes, 0, 3, &mut |_| Ok(()))?
                {
                    break accepted;
                }
            };
            assert!(accepted, "node {node}, saved inputs {save_inputs}");
        }
    }
    Ok(())
}

#[test]
fn symbol_lookahead_and_predicate_extras_are_narrow() -> Result<()> {
    let sum = Expr::WindowFunction(Box::new(WindowFunction::new(
        WindowFunctionDefinition::AggregateUDF(
            datafusion::functions_aggregate::sum::sum_udaf(),
        ),
        vec![col("x")],
    )));
    let next = Expr::WindowFunction(Box::new(WindowFunction::new(
        WindowFunctionDefinition::AggregateUDF(crate::functions::udaf::mr_next_udaf()),
        vec![
            col("x"),
            lit(1_u64),
            lit(0_i64),
            col(MatchMetadataColumn::Classifier.as_ref()).is_not_null(),
            crate::planning::logical::valid_match_row_expr(),
        ],
    )));
    let spec = compile_deferred_symbols(
        Field::new("x", DataType::Int64, false),
        Pattern::Concat(
            ["A", "B"]
                .into_iter()
                .map(|name| Pattern::Symbol(Symbol::Named(name.into())))
                .collect(),
        ),
        vec![
            LogicalSymbolInput::deferred("A", sum.eq(col("x"))),
            LogicalSymbolInput::deferred(
                "B",
                next.is_not_null()
                    .and(col(MatchMetadataColumn::MatchNumber.as_ref()).eq(lit(1_i64))),
            ),
        ],
    )?;
    assert_eq!(spec.max_lookahead_rows(), NavigationOffset::ONE);
    let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, false)]));
    let factory = DeferredEvaluatorFactory::try_from_spec(
        &spec,
        &DefaultPhysicalPlanner::default(),
        &SessionContext::new().state(),
        &PhysicalPlanningContext::default(),
        &schema,
        &[
            SymbolId::try_new(1, 3).unwrap(),
            SymbolId::try_new(2, 3).unwrap(),
        ],
        &[None, Some("A".into()), Some("B".into())],
    )?;
    for (symbol, lookahead, extra) in [
        (1, NavigationOffset::ZERO, "x"),
        (
            2,
            NavigationOffset::ONE,
            MatchMetadataColumn::MatchNumber.as_ref(),
        ),
    ] {
        let predicate = factory.program.predicates[symbol].as_ref().unwrap();
        assert_eq!(predicate.max_lookahead_rows, lookahead);
        assert_eq!(predicate.predicate_schema.fields().len(), 2);
        assert_eq!(predicate.extra_ordinals.len(), 1);
        assert_eq!(
            factory
                .program
                .history
                .schema
                .field(predicate.extra_ordinals[0])
                .name(),
            extra
        );
    }
    let collection = BatchCollection::try_new(
        vec![RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(Int64Array::from(vec![1, 99]))],
        )?],
        schema,
    )?;
    let memory = crate::execution::common::memory::new_unbounded_state_memory();
    let mut history = factory.candidate_history(&memory)?;
    let nodes = [PathNode {
        step: PathStep {
            row: AbsoluteRow::new(0),
            sym: Sym::from_index(1),
            excluded: false,
        },
        prev: None,
        depth: 0,
    }];
    history.begin(0, SymbolId::try_new(1, 3).unwrap(), 1)?;
    loop {
        if let Some(accepted) =
            history.advance(&collection, &nodes, 0, 2, &mut |_| Ok(()))?
        {
            assert!(accepted);
            break;
        }
    }
    assert_eq!(
        history.gathered_rows(),
        1,
        "A must not gather B's lookahead"
    );
    Ok(())
}