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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
// 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.

//! DataFusion physical operator for `MATCH_RECOGNIZE`.
//!
//! [`MatchRecognizePatternExec`] stores the prepared matcher program and starts
//! one output stream per input partition. `construction` prepares its child
//! layout, while `display` formats `EXPLAIN` output, including bound VM
//! instructions.
//!
//! Matching can discard or repeat input rows, so its cardinality effect is
//! unknown. Cardinality-sensitive reductions must remain above the matcher.

use datafusion::common::stats::Precision;
use datafusion::common::tree_node::TreeNodeRecursion;
use datafusion::common::{Result, exec_err, internal_err};
use datafusion::physical_expr::expressions::Column;
use datafusion::physical_plan::ColumnStatistics;
use datafusion::physical_plan::PhysicalExpr;
use datafusion::physical_plan::execution_plan::{
    ChildrenPropertiesMode, ReplaceChildrenOptions, Statistics,
};
use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricsSet};
use datafusion::physical_plan::repartition::RepartitionExec;
use datafusion::physical_plan::sorts::sort::SortExec;
use datafusion::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
use datafusion::physical_plan::statistics::{ChildStats, StatisticsArgs};
use datafusion::physical_plan::{
    DisplayAs, DisplayFormatType, ExecutionPlan, InputDistributionRequirements,
    SendableRecordBatchStream, apply_expression_roots,
};
use datafusion_hash_grouped_order::{
    BoundedPartitionFilter, GroupEmitOrder, GroupedOrderConsumer, GroupedOrderTarget,
    HashGroupedOrderExec, HashGroupedOrderRule, PartitionMaskExtractor,
};

use std::num::NonZeroUsize;
use std::sync::Arc;

use crate::config::MatchRecognizeConfig;
use crate::execution::physical::halo::{
    HALO_CHUNK_ID, HALO_GROUP_ID, HaloChunkExec, HaloFinalizeExec,
};
use crate::execution::physical::properties::{
    calc_requirements, get_partition_by_sort_exprs,
};

use crate::core::{EmptyMatchesMode, RowsPerMatch};
use crate::execution::matching::{
    ExecutableMatchProgram, ExecutableOutputFinalizer, ResolvedAfterMatchSkip,
};
use crate::nfa::PatternCompileLimits;
use crate::nfa_executor::{ExecutePatternInput, execute_pattern};
use datafusion::physical_expr_common::sort_expr::{
    LexOrdering, OrderingRequirements, PhysicalSortExpr,
};

mod construction;
mod display;
mod synthetic_row_filter;

pub use synthetic_row_filter::try_absorb_synthetic_row_filter;

pub(crate) use construction::PreparedPattern;
pub(crate) use construction::{
    MatchPlanLayout, PatternPreparationInput, prepare_pattern, runtime_symbol_ids,
    validate_compiled_symbol_alignment,
};
pub(crate) use display::MatchPlanDisplay;
use display::format_exec_display;

/// How long the partitioned stream must retain an open logical partition.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PartitionRetention {
    /// Threshold flushing is safe for this pattern and evaluator program.
    ThresholdSafe,
    /// Flush only after the logical partition boundary is known.
    LogicalPartitionBoundaryOnly,
}

/// Records that a query passed the core-and-halo checks and stores its finite
/// maximum match length.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct HaloQualification {
    max_match_len: NonZeroUsize,
}

impl HaloQualification {
    fn for_program(program: &ExecutableMatchProgram) -> Option<Self> {
        let automaton = program.compiled_automaton();
        // Halo duplicates rows and changes physical neighbor boundaries.
        if !program.can_skip_candidate_evaluation
            || program.offset_columns.is_some()
            || program
                .classification
                .as_ref()
                .is_some_and(|c| c.needs_neighbors())
            || automaton.has_anchors()
            || !program.stream_requirements().independent_candidate_starts
            || automaton.min_match_rows() == 0
        {
            return None;
        }

        let max_match_len = NonZeroUsize::new(automaton.max_match_rows()?)?;
        let independent_skip = match program.after_match_skip() {
            ResolvedAfterMatchSkip::ToNextRow => true,
            ResolvedAfterMatchSkip::PastLastRow => {
                max_match_len.get() == 1 || program.non_overlapping_starts
            }
            _ => false,
        };
        if !independent_skip || !program.output_spec().navigation_offsets().is_zero() {
            return None;
        }

        match program.rows_per_match() {
            RowsPerMatch::OneRow
            | RowsPerMatch::AllRows(EmptyMatchesMode::Show | EmptyMatchesMode::Omit) => {
                Some(Self { max_match_len })
            }
            RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched) => None,
        }
    }

    pub(crate) const fn max_match_len(self) -> usize {
        self.max_match_len.get()
    }
}

impl PartitionRetention {
    pub(crate) fn for_program(program: &ExecutableMatchProgram) -> Self {
        if program.compiled_automaton().has_end_anchor()
            || program.stream_requirements().needs_complete_partition
        {
            Self::LogicalPartitionBoundaryOnly
        } else {
            Self::ThresholdSafe
        }
    }
}

/// Planning decisions applied to each execution of the physical operator.
#[derive(Clone, Copy, Debug)]
pub(crate) struct PlannedRuntimePolicy {
    pattern_compile_limits: PatternCompileLimits,
    compact_paths_disabled: bool,
    retention: PartitionRetention,
    parallel_qualification: Option<HaloQualification>,
}

impl PlannedRuntimePolicy {
    pub(crate) fn new(
        bound: &BoundMatchPlan,
        pattern_compile_limits: PatternCompileLimits,
        compact_paths_disabled: bool,
    ) -> Self {
        let program = bound.program.as_ref();
        Self {
            pattern_compile_limits,
            compact_paths_disabled,
            retention: PartitionRetention::for_program(program),
            parallel_qualification: HaloQualification::for_program(program),
        }
    }

    pub(crate) const fn retention(self) -> PartitionRetention {
        self.retention
    }

    pub(crate) const fn parallel_qualification(self) -> Option<HaloQualification> {
        self.parallel_qualification
    }

    pub(in crate::execution) fn apply(
        self,
        mut config: MatchRecognizeConfig,
    ) -> MatchRecognizeConfig {
        config.diagnostics.disable_compact_paths |= self.compact_paths_disabled;
        config.limits.pattern_max_permute_branches =
            self.pattern_compile_limits.max_permute_branches;
        config.limits.pattern_max_nfa_states = self.pattern_compile_limits.max_nfa_states;
        config.limits.pattern_max_epsilon_closure_entries =
            self.pattern_compile_limits.max_epsilon_closure_entries;
        config.limits.pattern_max_dense_transition_cells =
            self.pattern_compile_limits.max_dense_transition_cells;
        config
    }

    fn for_halo(self) -> Self {
        Self {
            retention: PartitionRetention::LogicalPartitionBoundaryOnly,
            parallel_qualification: None,
            ..self
        }
    }
}

/// Input layout, executable program, and display data for the physical operator.
#[derive(Clone, Debug)]
pub(in crate::execution) struct BoundMatchPlan {
    layout: MatchPlanLayout,
    program: Arc<ExecutableMatchProgram>,
    display: MatchPlanDisplay,
}

impl BoundMatchPlan {
    pub(in crate::execution) fn from_checked_parts(
        layout: MatchPlanLayout,
        program: Arc<ExecutableMatchProgram>,
        display: MatchPlanDisplay,
    ) -> Self {
        Self {
            layout,
            program,
            display,
        }
    }
}

/// DataFusion physical operator that finds row-pattern matches.
///
/// It runs the NFA matcher, applies `DEFINE` predicates and `AFTER MATCH SKIP`,
/// and materializes the planned row or summary output, including requested
/// match metadata.
#[derive(Debug)]
pub struct MatchRecognizePatternExec {
    /// Input layout, executable program, and display data.
    bound: BoundMatchPlan,
    /// Planning decisions applied to each runtime session configuration.
    policy: PlannedRuntimePolicy,
    /// Programmatic floating keys can retain Arrow's raw total-order identity.
    raw_float_groups: bool,
    /// Rows where a match may start within each physical halo partition.
    candidate_start_core_rows: Option<NonZeroUsize>,
    /// Baseline metrics shared by partition-local streams.
    metrics: ExecutionPlanMetricsSet,
}

impl MatchRecognizePatternExec {
    pub(super) fn with_match_aware_input(
        mut self,
        mr: &crate::planning::logical::MatchRecognize,
        allow_windows: bool,
        binder: &mut crate::execution::physical::planner::bind::PhysicalMatchBinder<'_>,
    ) -> Result<Self> {
        use crate::execution::physical::{classification, virtual_input};
        let aware = self.bound.program.as_ref();
        let layout = &self.bound.layout;
        let order = layout.order_by.as_deref().unwrap_or_default();
        let bound = classification::bind_post_order_input(
            &layout.input,
            aware,
            mr,
            &layout.partition_by,
            order,
            allow_windows,
        )?;
        let had_classification = bound.is_some();
        let mut bound = bound.unwrap_or_else(|| classification::BoundInput {
            input: layout.input.clone(),
            classification: None,
            offsets: None,
            rules: Vec::new(),
            unused_window_columns: std::collections::HashSet::new(),
        });
        let compact = if allow_windows {
            virtual_input::compact(mr, aware, &mut bound, &layout.partition_by, order)?
        } else {
            None
        };
        if !had_classification && compact.is_none() {
            return Ok(self);
        }
        let mapping = if let Some(compact) = compact {
            if let Some((logical, full)) = compact.rebound {
                // A fresh binding must not restore bypass after raw float groups
                // or halo planning required ordered, partitioned input.
                let bypass =
                    self.bound.layout.bypass_never_ordering && !self.raw_float_groups;
                self.bound = binder.bind(&logical, &[full])?;
                self.bound.layout = self
                    .bound
                    .layout
                    .rebuild_with_bypass(bypass, self.bound.program.as_ref())?;
            }
            bound.input = compact.input;
            Some(Arc::new(compact.mapping))
        } else {
            None
        };
        let program = Arc::make_mut(&mut self.bound.program);
        let aware = &mut *program;
        aware.virtual_input = mapping;
        // Absorbed Boolean fields are placeholders after this point. Rebuild
        // the filter from raw classifier inputs instead of retaining stale slots.
        aware.pre_sort_filter = None;
        if let Some(classification) = bound.classification {
            if aware.can_skip_candidate_evaluation {
                if bound.offsets.is_none() {
                    aware.pre_sort_filter = classification.partition_filter(
                        aware.base_variant().automaton().required_anchors(),
                    );
                }
                aware.packed_anchors =
                    crate::execution::classification::PackedAnchors::bind(
                        &classification,
                        aware.base_variant().automaton(),
                    )
                    .map(Arc::new);
            }
            aware.classification = Some(Arc::new(classification));
        }
        aware.offset_columns = bound.offsets.map(Arc::new);
        self.policy.parallel_qualification = HaloQualification::for_program(aware);
        self.bound.layout = self.bound.layout.rebuild_with_input(bound.input, program)?;
        Ok(self)
    }

    fn rebuild_with_child(
        &self,
        input: Arc<dyn ExecutionPlan>,
        properties_mode: ChildrenPropertiesMode,
    ) -> Result<Self> {
        // The executable program holds checked physical column indices. A
        // property rebuild does not rebind those indices, including prepared
        // Boolean DEFINE slots, output columns, and partition/order keys.
        if input.schema() != self.bound.layout.input.schema() {
            return internal_err!(
                "MATCH_RECOGNIZE replacement child schema must equal the prepared input schema"
            );
        }
        let layout = match properties_mode {
            ChildrenPropertiesMode::Keep
                if self.grouped_input().is_none()
                    && input.downcast_ref::<HashGroupedOrderExec>().is_none() =>
            {
                MatchPlanLayout {
                    input,
                    ..self.bound.layout.clone()
                }
            }
            _ => self
                .bound
                .layout
                .rebuild_with_input(input, self.program().as_ref())?,
        };
        Ok(Self {
            bound: BoundMatchPlan::from_checked_parts(
                layout,
                Arc::clone(self.program()),
                self.bound.display.clone(),
            ),
            policy: self.policy,
            raw_float_groups: self.raw_float_groups,
            candidate_start_core_rows: self.candidate_start_core_rows,
            metrics: ExecutionPlanMetricsSet::new(),
        })
    }

    /// Construct the operator from records already checked by physical planning.
    pub(super) fn new(bound: BoundMatchPlan, policy: PlannedRuntimePolicy) -> Self {
        Self {
            bound,
            policy,
            raw_float_groups: false,
            candidate_start_core_rows: None,
            metrics: ExecutionPlanMetricsSet::new(),
        }
    }

    pub(super) fn with_raw_float_groups(mut self, raw_float_groups: bool) -> Self {
        self.raw_float_groups = raw_float_groups;
        if raw_float_groups && self.bound.layout.bypass_never_ordering {
            self.bound.layout = self
                .bound
                .layout
                .rebuild_with_bypass(false, self.program().as_ref())
                .expect("recomputing layout for raw float groups");
        }
        self
    }

    pub(crate) fn with_candidate_start_core_rows(
        mut self,
        core_rows: NonZeroUsize,
    ) -> Self {
        self.candidate_start_core_rows = Some(core_rows);
        if self.bound.layout.bypass_never_ordering {
            self.bound.layout = self
                .bound
                .layout
                .rebuild_with_bypass(false, self.program().as_ref())
                .expect("recomputing layout for halo core rows");
        }
        self
    }

    pub(crate) fn into_halo_pipeline(
        self,
        core_rows: NonZeroUsize,
        output_partitions: usize,
        qualification: HaloQualification,
        private_chunk: bool,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        if output_partitions == 0 {
            return internal_err!(
                "MATCH_RECOGNIZE halo pipeline requires an output partition"
            );
        }

        let original_program = Arc::clone(self.program());
        let needs_match_numbers = original_program
            .output_plan()
            .match_number_column()
            .is_some();
        let original_ordering = self.bound.layout.order_by.clone();
        let partition_by = self.bound.layout.partition_by.clone();
        let keyed = !partition_by.is_empty();
        let required_input_ordering = if keyed {
            let mut required_ordering = self.partition_by_sort_keys()?;
            if let Some(ordering) = &original_ordering {
                for sort_expr in ordering {
                    if !required_ordering
                        .iter()
                        .any(|existing| existing.expr.eq(&sort_expr.expr))
                    {
                        required_ordering.push(sort_expr.clone());
                    }
                }
            }
            LexOrdering::new(required_ordering)
        } else {
            original_ordering.clone()
        };
        let halo = HaloChunkExec::try_new(
            Arc::clone(&self.bound.layout.input),
            required_input_ordering,
            original_ordering.clone(),
            partition_by,
            core_rows.get(),
            qualification.max_match_len(),
        )?;
        let group_input_index = halo.group_column_index();
        let chunk_input_index = halo.chunk_column_index();
        let schema_without_chunk = halo.schema_without_chunk();
        let halo: Arc<dyn ExecutionPlan> = Arc::new(halo);
        let group_input_expr = group_input_index.map(|index| {
            Arc::new(Column::new(HALO_GROUP_ID, index)) as Arc<dyn PhysicalExpr>
        });
        let chunk_input_expr = Arc::new(Column::new(HALO_CHUNK_ID, chunk_input_index))
            as Arc<dyn PhysicalExpr>;
        let mut private_input_exprs = Vec::with_capacity(1 + usize::from(keyed));
        if let Some(group_input_expr) = &group_input_expr {
            private_input_exprs.push(Arc::clone(group_input_expr));
        }
        private_input_exprs.push(Arc::clone(&chunk_input_expr));
        let repartition = RepartitionExec::try_new(
            halo,
            datafusion::physical_plan::Partitioning::Hash(
                private_input_exprs.clone(),
                output_partitions,
            ),
        )?
        .with_preserve_order();
        let repartition: Arc<dyn ExecutionPlan> = Arc::new(repartition);
        let halo_program = Arc::new(if private_chunk {
            original_program
                .with_appended_passthrough(&repartition.schema(), chunk_input_index)?
        } else if needs_match_numbers {
            let with_group = match group_input_index {
                Some(group_input_index) => original_program.with_appended_passthrough(
                    &schema_without_chunk,
                    group_input_index,
                )?,
                None => original_program.as_ref().clone(),
            };
            with_group
                .with_appended_passthrough(&repartition.schema(), chunk_input_index)?
        } else {
            // Private keys still partition input and bound core-owned starts.
            // Only global match-number finalization needs them in output.
            // Keeping the original output also lets pruned summaries retain
            // just cardinality instead of gathering discarded chunk IDs.
            original_program.with_extended_input_schema(&repartition.schema())?
        });
        let layout = MatchPlanLayout::try_new(
            repartition,
            private_input_exprs,
            original_ordering,
            halo_program.as_ref(),
        )?;
        let match_number_column = halo_program
            .output_plan()
            .match_number_column()
            .map(|column| column.index());
        let matcher = MatchRecognizePatternExec::new(
            BoundMatchPlan::from_checked_parts(
                layout,
                halo_program,
                self.bound.display.clone(),
            ),
            self.policy.for_halo(),
        )
        .with_candidate_start_core_rows(core_rows);
        let matcher: Arc<dyn ExecutionPlan> = Arc::new(matcher);
        if private_chunk {
            let chunk = original_program
                .output_spec()
                .passthrough_input_indices()
                .len();
            return super::halo::project_group_chunk(matcher, Some(chunk));
        }
        if match_number_column.is_none() {
            return Ok(matcher);
        }
        let original_schema = Arc::clone(original_program.output_schema());
        let first_hidden_output_index = original_program
            .output_spec()
            .passthrough_input_indices()
            .len();
        let group_output_index = keyed.then_some(first_hidden_output_index);
        let chunk_output_index = first_hidden_output_index + usize::from(keyed);
        let mut merge_ordering = Vec::with_capacity(1 + usize::from(keyed));
        if let Some(group_output_index) = group_output_index {
            merge_ordering.push(PhysicalSortExpr {
                expr: Arc::new(Column::new(HALO_GROUP_ID, group_output_index)),
                options: datafusion::arrow::compute::SortOptions::new(false, false),
            });
        }
        merge_ordering.push(PhysicalSortExpr {
            expr: Arc::new(Column::new(HALO_CHUNK_ID, chunk_output_index)),
            options: datafusion::arrow::compute::SortOptions::new(false, false),
        });
        let chunk_output_ordering = LexOrdering::new(merge_ordering)
            .expect("halo merge key makes the ordering nonempty");
        let merged: Arc<dyn ExecutionPlan> =
            Arc::new(SortPreservingMergeExec::new(chunk_output_ordering, matcher));
        let finalized = HaloFinalizeExec::try_new(
            merged,
            original_schema,
            group_output_index,
            chunk_output_index,
            match_number_column,
        )?;
        Ok(Arc::new(finalized))
    }

    pub(crate) fn program(&self) -> &Arc<ExecutableMatchProgram> {
        &self.bound.program
    }

    pub(in crate::execution) const fn policy(&self) -> PlannedRuntimePolicy {
        self.policy
    }

    /// Return the partition key expressions and options in boundary-encoding order.
    /// A grouped producer supplies these even when different keys leave in hash order.
    pub fn partition_by_sort_keys(&self) -> Result<Vec<PhysicalSortExpr>> {
        if let Some(group) = self.grouped_input() {
            return Ok(group
                .output_group_keys()
                .iter()
                .zip(group.partition_sort_options())
                .map(|(expr, options)| PhysicalSortExpr::new(Arc::clone(expr), *options))
                .collect());
        }
        if self.can_bypass_ordering_for_never() {
            return Ok(vec![]);
        }
        if self.bound.layout.ordered_partition_by_indices.len()
            != self.bound.layout.partition_by.len()
        {
            return exec_err!(
                "MATCH_RECOGNIZE requires ordered input covering every PARTITION BY key"
            );
        }
        get_partition_by_sort_exprs(
            &self.bound.layout.input,
            &self.bound.layout.partition_by,
            &self.bound.layout.ordered_partition_by_indices,
        )
    }

    /// Return the expressions DataFusion uses to repartition the input.
    pub fn partition_keys(&self) -> Vec<Arc<dyn PhysicalExpr>> {
        self.bound.layout.partition_by.clone()
    }

    /// When the pattern is statically impossible (`NormalizedPattern::Never`),
    /// no unmatched rows are emitted, no matcher-side navigation/on-demand
    /// predicates can fail, and every `PARTITION BY`/`ORDER BY` key is a plain
    /// infallible column reference, the matcher emits zero rows regardless of
    /// input order or partitioning while still draining its child stream so
    /// upstream I/O and SQL errors surface normally.
    fn can_bypass_ordering_for_never(&self) -> bool {
        self.bound.layout.bypass_never_ordering
            && self.candidate_start_core_rows.is_none()
            && !self.raw_float_groups
    }
}

impl DisplayAs for MatchRecognizePatternExec {
    fn fmt_as(
        &self,
        _t: DisplayFormatType,
        f: &mut std::fmt::Formatter,
    ) -> std::fmt::Result {
        format_exec_display(self, f)
    }
}

impl ExecutionPlan for MatchRecognizePatternExec {
    fn name(&self) -> &'static str {
        Self::static_name()
    }

    fn properties(
        &self,
    ) -> &Arc<datafusion::physical_plan::execution_plan::PlanProperties> {
        &self.bound.layout.cache
    }

    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
        vec![&self.bound.layout.input]
    }

    fn apply_expressions(
        &self,
        f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
    ) -> Result<TreeNodeRecursion> {
        let program_roots = self.program().physical_expr_roots();
        let layout_roots = self.bound.layout.partition_by.iter();
        apply_expression_roots(layout_roots.chain(program_roots.iter()), f)
    }

    fn replace_children(
        self: Arc<Self>,
        mut children: Vec<Arc<dyn ExecutionPlan>>,
        options: ReplaceChildrenOptions,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        if children.len() != 1 {
            return internal_err!(
                "MatchRecognizePatternExec expected 1 child, got {}",
                children.len()
            );
        }

        let input = children.swap_remove(0);
        Ok(Arc::new(
            self.rebuild_with_child(input, options.children_properties)?,
        ))
    }

    fn with_new_children(
        self: Arc<Self>,
        children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        self.replace_children(
            children,
            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
        )
    }

    fn execute(
        &self,
        partition: usize,
        context: Arc<datafusion::execution::TaskContext>,
    ) -> Result<SendableRecordBatchStream> {
        log::debug!("Executing MatchRecognizePatternExec for partition {partition}");
        let flush_threshold = context.session_config().batch_size();

        // Read session settings when registered; otherwise use the defaults.
        let mr_config = context
            .session_config()
            .options()
            .extensions
            .get::<MatchRecognizeConfig>()
            .cloned()
            .unwrap_or_default();
        let mr_config = self.policy.apply(mr_config);

        use crate::execution::stream::MatchInput;
        let input_stream = match self.grouped_input() {
            Some(grouped) => {
                let needed = Some(
                    self.program()
                        .referenced_input_columns(grouped.schema().fields().len()),
                );
                MatchInput::Grouped(grouped.execute_grouped_with_needed_columns(
                    partition,
                    Arc::clone(&context),
                    needed,
                )?)
            }
            None => MatchInput::Ordered(
                self.bound
                    .layout
                    .input
                    .execute(partition, Arc::clone(&context))?,
            ),
        };

        log::debug!(
            "Calling execute_pattern with interleaves_logical_partitions={}",
            self.program()
                .stream_requirements()
                .interleaves_logical_partitions
        );

        execute_pattern(ExecutePatternInput {
            input: input_stream,
            program: Arc::clone(&self.bound.program),
            partition_by_sort_keys: self.partition_by_sort_keys()?,
            retention: self.policy.retention(),
            candidate_start_core_rows: self.candidate_start_core_rows,
            // Small cores need session-sized batches; large cores must not shrink
            // their output batches and stall workers behind the ordered merge.
            output_batch_size: self
                .candidate_start_core_rows
                .and_then(|core| NonZeroUsize::new(core.get().max(flush_threshold))),
            flush_threshold,
            config: mr_config,
            metrics_set: self.metrics.clone(),
            task_context: context,
            partition,
        })
    }

    fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
        vec![ChildStats::At(partition)]
    }

    fn statistics_from_inputs(
        &self,
        input_stats: &[Arc<Statistics>],
        _args: &StatisticsArgs,
    ) -> Result<Arc<Statistics>> {
        let [input_stats] = input_stats else {
            return internal_err!(
                "MatchRecognizePatternExec expected statistics for 1 child, got {}",
                input_stats.len()
            );
        };
        Ok(Arc::new(compute_partition_statistics(
            input_stats.as_ref(),
            self.program(),
        )))
    }

    fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
        // The direct group stream guarantees contiguous keys and within-key order.
        // Its producer owns any upstream ordering required by the Linear mode.
        if self.grouped_input().is_some() || self.can_bypass_ordering_for_never() {
            return vec![None];
        }
        // Require every partition key before the within-partition ordering.
        let partition_bys = &self.bound.layout.partition_by;
        let order_keys: &[PhysicalSortExpr] = match &self.bound.layout.order_by {
            Some(v) => &v[..],
            None => &[],
        };

        let requirement = if self.bound.layout.ordered_partition_by_indices.len()
            < partition_bys.len()
        {
            calc_requirements(partition_bys, order_keys)
        } else {
            let reordered: Vec<_> = self
                .bound
                .layout
                .ordered_partition_by_indices
                .iter()
                .map(|idx| Arc::clone(&partition_bys[*idx]))
                .collect();
            calc_requirements(&reordered, order_keys)
        };

        vec![requirement]
    }

    fn input_distribution_requirements(&self) -> InputDistributionRequirements {
        if self.can_bypass_ordering_for_never() {
            return InputDistributionRequirements::new(vec![
                datafusion::physical_plan::Distribution::UnspecifiedDistribution,
            ]);
        }
        let keys = self.partition_keys();

        let distribution = if keys.is_empty() {
            datafusion::physical_plan::Distribution::SinglePartition
        } else {
            datafusion::physical_plan::Distribution::KeyPartitioned(keys)
        };

        InputDistributionRequirements::new(vec![distribution])
    }

    /// Report whether output preserves row order within each physical partition.
    ///
    /// Order is preserved only if:
    /// - `AFTER MATCH SKIP` is `PastLastRow`, so matches do not overlap;
    /// - PREV/NEXT output offsets are zero, so no navigation context can reorder rows;
    /// - the rows-per-match mode does not emit unmatched rows; and
    /// - Deferred evaluation cannot interleave multiple logical partitions.
    ///
    /// Navigation context invalidates inherited input ordering, while valid
    /// match-number/sequence orderings remain available in the plan properties.
    /// DataFusion supplies sorting when a consumer requires it.
    fn maintains_input_order(&self) -> Vec<bool> {
        vec![self.bound.layout.maintains_input_order]
    }

    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
        vec![!self.can_bypass_ordering_for_never()]
    }

    fn metrics(&self) -> Option<MetricsSet> {
        Some(self.metrics.clone_inner().with_output_rows_skew())
    }
}

/// Project child statistics onto the columns emitted by `MATCH_RECOGNIZE`.
///
/// Projects input statistics to the output schema and adds unknown statistics
/// for generated columns (metadata, classifier bitsets, and summaries).
fn compute_partition_statistics(
    input_stats: &Statistics,
    program: &ExecutableMatchProgram,
) -> Statistics {
    let output_spec = program.output_spec();
    // Row finalizers, including non-native ONE ROW summaries, can emit the
    // same consuming rows after a restart.
    let overlaps = matches!(
        program.output_plan().finalizer(),
        ExecutableOutputFinalizer::Rows
    ) && !matches!(
        program.after_match_skip(),
        ResolvedAfterMatchSkip::PastLastRow
    ) && program
        .compiled_automaton()
        .max_match_rows()
        .is_none_or(|max_rows| max_rows > 1);
    // The output stream can also repeat rows as PREV/NEXT context for each
    // match. Native summaries and inline running PREV/NEXT keep context private.
    let can_repeat_rows = overlaps
        || program
            .output_plan()
            .stream()
            .emits_navigation_buffer_rows();

    // Keep statistics for selected passthrough columns in output order.
    let mut column_statistics: Vec<ColumnStatistics> = Vec::new();
    for &input_idx in output_spec.passthrough_input_indices() {
        let mut column = input_stats
            .column_statistics
            .get(input_idx)
            .cloned()
            .unwrap_or_else(ColumnStatistics::new_unknown);
        if can_repeat_rows {
            column.null_count = Precision::Absent;
            column.sum_value = Precision::Absent;
            column.byte_size = Precision::Absent;
        }
        column_statistics.push(column);
    }

    // Generated metadata columns have no useful child statistics.
    for _ in output_spec.metadata_columns() {
        column_statistics.push(ColumnStatistics::new_unknown());
    }

    // Classifier bitsets are also generated by this operator.
    for _ in output_spec.classifier_bitset_symbols() {
        column_statistics.push(ColumnStatistics::new_unknown());
    }

    for _ in 0..program.output_plan().summary_count() {
        column_statistics.push(ColumnStatistics::new_unknown());
    }

    let (num_rows, total_byte_size) = if can_repeat_rows {
        (Precision::Absent, Precision::Absent)
    } else {
        (input_stats.num_rows, input_stats.total_byte_size)
    };
    Statistics {
        num_rows,
        total_byte_size,
        column_statistics,
    }
    .to_inexact()
}

impl MatchRecognizePatternExec {
    /// Return row-local evidence that can rule out every match in a partition.
    /// A surviving partition still feeds all its rows to the matcher.
    pub fn pre_sort_partition_filter(&self) -> Option<Arc<dyn PartitionMaskExtractor>> {
        let program = self.program().as_ref();
        let automaton = program.compiled_automaton();
        let min_rows = automaton.min_match_rows();
        if self.candidate_start_core_rows.is_some()
            || self.bound.layout.partition_by.is_empty()
            || min_rows == 0
            || program.rows_per_match()
                == &RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
        {
            return None;
        }
        // Only whole-partition anchored patterns (`^ ... $`) impose an upper
        // bound on partition length.
        let max_rows = (automaton.has_mandatory_start_anchor_prefix()
            && automaton.anchored_at_end())
        .then(|| automaton.max_match_rows())
        .flatten();
        if !program.can_skip_candidate_evaluation
            || program.offset_columns.is_some()
            || program
                .classification
                .as_ref()
                .is_some_and(|c| c.needs_neighbors())
        {
            return None;
        }
        BoundedPartitionFilter::wrap(program.pre_sort_filter.clone(), min_rows, max_rows)
    }
}

/// Construct a grouping rule restricted to SQL row-pattern matching.
/// The caller chooses whether ancestors need cross-key order for this input.
pub fn match_recognize_grouped_order_rule(
    emit_order: GroupEmitOrder,
    prune_partitions: bool,
) -> HashGroupedOrderRule {
    HashGroupedOrderRule::with_consumers(
        Default::default(),
        vec![Arc::new(MatcherConsumer {
            emit_order,
            prune_partitions,
        })],
    )
}

#[derive(Debug)]
struct MatcherConsumer {
    emit_order: GroupEmitOrder,
    prune_partitions: bool,
}

impl GroupedOrderConsumer for MatcherConsumer {
    fn partition_zeros_normalized(&self) -> bool {
        // match_consumer excludes raw programmatic floating partition keys.
        true
    }

    fn match_consumer(&self, node: &dyn ExecutionPlan) -> Option<GroupedOrderTarget> {
        let matcher = node.downcast_ref::<MatchRecognizePatternExec>()?;
        let layout = &matcher.bound.layout;
        let sort = layout.input.downcast_ref::<SortExec>()?;
        // Halo core selection is in physical chunk coordinates. Its logical
        // partition key is not a certificate for grouping complete SQL partitions.
        // Raw programmatic floating keys distinguish signed zeros and NaN
        // payloads. The grouped engine uses SQL grouping equality instead.
        if matcher.candidate_start_core_rows.is_some()
            || matcher.raw_float_groups
            || !within_key_order(
                layout.partition_by.as_slice(),
                layout.order_by.as_ref(),
                sort.expr().get(layout.partition_by.len()..)?,
            )
        {
            return None;
        }
        Some(GroupedOrderTarget {
            partition_by: layout.partition_by.clone(),
            emit_order: self.emit_order,
            partition_filter: self
                .prune_partitions
                .then(|| matcher.pre_sort_partition_filter())
                .flatten(),
        })
    }
}

/// A stronger suffix can break ties, but the requested order must come first.
/// Partition keys in ORDER BY are constant inside their own logical group.
fn within_key_order(
    keys: &[Arc<dyn PhysicalExpr>],
    required: Option<&LexOrdering>,
    actual: &[PhysicalSortExpr],
) -> bool {
    let is_key = |sort: &PhysicalSortExpr| keys.iter().any(|key| key.eq(&sort.expr));
    let mut available = actual.iter().filter(|sort| !is_key(sort));
    required
        .into_iter()
        .flat_map(|ordering| ordering.iter())
        .filter(|sort| !is_key(sort))
        .all(|wanted| available.next() == Some(wanted))
}

fn compatible_group(
    group: &HashGroupedOrderExec,
    keys: &[Arc<dyn PhysicalExpr>],
    order: Option<&LexOrdering>,
) -> bool {
    // A replacement child may share the schema and have entirely different
    // grouping semantics. Require the same key set in either permutation.
    keys.len() == group.output_group_keys().len()
        && group
            .output_group_keys()
            .iter()
            .all(|key| keys.iter().any(|k| k.eq(key)))
        && keys
            .iter()
            .all(|key| group.output_group_keys().iter().any(|k| k.eq(key)))
        && within_key_order(keys, order, group.output_group_order())
}

impl MatchRecognizePatternExec {
    fn grouped_input(&self) -> Option<&HashGroupedOrderExec> {
        if self.bound.layout.grouped_input
            && self.candidate_start_core_rows.is_none()
            && !self.raw_float_groups
        {
            self.bound
                .layout
                .input
                .downcast_ref::<HashGroupedOrderExec>()
        } else {
            None
        }
    }

    pub(crate) fn uses_unordered_grouped_input(&self) -> bool {
        self.grouped_input()
            .is_some_and(|group| group.properties().output_ordering().is_none())
    }
}

#[cfg(test)]
mod stateful_tests;
#[cfg(test)]
mod tests;