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
// 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.

//! Converts `MatchRecognize` logical nodes into physical operators.
//!
//! Other logical nodes are passed to DataFusion's default physical planner.

use crate::config::MatchRecognizeConfig;
use crate::execution::physical::exec::{MatchRecognizePatternExec, PlannedRuntimePolicy};
use async_trait::async_trait;
use datafusion::catalog::Session;
use datafusion::common::tree_node::{Transformed, TreeNode};
use datafusion::common::{Column, DataFusionError, Result};
use datafusion::execution::context::QueryPlanner;
use datafusion::logical_expr::{
    Aggregate, Expr, ExprSchemable, Extension, LogicalPlan, Projection, col,
    expr::physical_name, physical_planning_context::PhysicalPlanningContext,
};
use datafusion::physical_expr::aggregate::LoweredAggregateBuilder;
use datafusion::physical_expr::expressions::Column as PhysicalColumn;
use datafusion::physical_expr::projection::ProjectionExpr;
use datafusion::physical_plan::aggregates::{
    AggregateExec, AggregateMode, PhysicalGroupBy,
};
use datafusion::physical_plan::execution_plan::Boundedness;
use datafusion::physical_plan::projection::ProjectionExec;
use datafusion::physical_plan::statistics::{StatisticsArgs, StatisticsContext};
use datafusion::physical_plan::{ExecutionPlan, ExecutionPlanProperties};
use datafusion::physical_planner::{
    DefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner,
};
use std::num::NonZeroUsize;

use crate::core::{
    EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeOutputSpec, MatchSummaryField,
    RowsPerMatch,
};
use crate::planning::logical::{
    LogicalMatchOutput, LogicalSelectedMatchSummary, MatchRecognize, is_matched_expr,
    selected_row_filter_expr, valid_match_row_expr,
};
use std::borrow::Cow;
use std::fmt;
use std::sync::Arc;

pub(in crate::execution) mod bind;
use bind::PhysicalMatchBinder;

/// Query planner that recognizes `MatchRecognize` logical nodes.
///
/// This planner intercepts MATCH_RECOGNIZE nodes and converts them to
/// `MatchRecognizePatternExec` physical plans. All other nodes
/// are delegated to the default physical planner.
///
/// # Integration
///
/// Applications should integrate through the public `datafusion-match-recognize`
/// API crate. Installing only `MatchRecognizeQueryPlanner` omits function,
/// source-adapter and logical-optimizer registration. Use
/// `new_match_recognize_context()` for the complete installation.
pub struct MatchRecognizeQueryPlanner {
    /// Default planner, configured with the extension planner below.
    default_planner: DefaultPhysicalPlanner,
}

impl fmt::Debug for MatchRecognizeQueryPlanner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MatchRecognizeQueryPlanner").finish()
    }
}

impl MatchRecognizeQueryPlanner {
    /// Create a new MatchRecognizeQueryPlanner.
    pub fn new() -> Self {
        Self::with_extension_planners(Vec::new())
    }

    /// Create a planner that keeps the supplied physical extension planners.
    ///
    /// The supplied planners retain their order and are tried before the
    /// `MATCH_RECOGNIZE` extension planner.
    pub fn with_extension_planners(
        mut extension_planners: Vec<Arc<dyn ExtensionPlanner + Send + Sync>>,
    ) -> Self {
        extension_planners.push(match_recognize_extension_planner());
        let default_planner =
            DefaultPhysicalPlanner::with_extension_planners(extension_planners);

        Self { default_planner }
    }
}

impl Default for MatchRecognizeQueryPlanner {
    fn default() -> Self {
        Self::new()
    }
}

/// Handles physical construction of `MatchRecognize` extension nodes.
#[derive(Debug)]
struct MatchRecognizeExtensionPlanner;

/// Return the physical extension planner for `MATCH_RECOGNIZE` logical nodes.
///
/// The crate root exposes this through its manual integration API so a host
/// can add it to a query planner that already handles other extension nodes.
/// The host must also install this crate's functions and optimizer rules.
pub fn match_recognize_extension_planner() -> Arc<dyn ExtensionPlanner + Send + Sync> {
    Arc::new(MatchRecognizeExtensionPlanner)
}

#[async_trait]
impl ExtensionPlanner for MatchRecognizeExtensionPlanner {
    async fn plan_extension(
        &self,
        planner: &dyn PhysicalPlanner,
        node: &dyn datafusion::logical_expr::UserDefinedLogicalNode,
        _logical_inputs: &[&LogicalPlan],
        physical_inputs: &[Arc<dyn ExecutionPlan>],
        session_state: &dyn Session,
        planning_ctx: &PhysicalPlanningContext,
    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
        if let Some(window) = node
            .as_any()
            .downcast_ref::<super::running_window::MatchWindow>()
        {
            return super::running_window::plan(
                window,
                Arc::clone(&physical_inputs[0]),
                planner,
                session_state,
                planning_ctx,
            )
            .map(Some);
        }
        if let Some(matcher) = node.as_any().downcast_ref::<MatchRecognize>()
            && let Some(grouped) = matcher.grouped_output_plan()?
        {
            return plan_grouped_output(
                planner,
                &grouped,
                physical_inputs,
                session_state,
                planning_ctx,
            )
            .map(Some);
        }
        plan_match_recognize_extension(
            planner,
            node,
            physical_inputs,
            session_state,
            planning_ctx,
        )
    }
}

/// Directly plan the fallback `Projection(Aggregate(Projection*(rows)))`
/// subtree emitted by [`MatchRecognize::grouped_output_plan`] without
/// invoking `PhysicalPlanner::create_physical_plan` recursively.
///
/// Running a nested `create_physical_plan` would run physical optimizers
/// (including materialized-CTE scan binding) on a partial subtree before outer
/// CTEs or `LIMIT`s exist, and would drop `planning_ctx`.
fn plan_grouped_output(
    planner: &dyn PhysicalPlanner,
    plan: &LogicalPlan,
    physical_inputs: &[Arc<dyn ExecutionPlan>],
    session_state: &dyn Session,
    planning_ctx: &PhysicalPlanningContext,
) -> Result<Arc<dyn ExecutionPlan>> {
    match plan {
        LogicalPlan::Extension(ext) => plan_match_recognize_extension(
            planner,
            ext.node.as_ref(),
            physical_inputs,
            session_state,
            planning_ctx,
        )?
        .ok_or_else(|| {
            DataFusionError::Internal(
                "unexpected Extension node in grouped MATCH_RECOGNIZE output".into(),
            )
        }),
        LogicalPlan::Projection(projection) => {
            let input_exec = plan_grouped_output(
                planner,
                projection.input.as_ref(),
                physical_inputs,
                session_state,
                planning_ctx,
            )?;
            plan_grouped_projection(
                planner,
                projection,
                input_exec,
                session_state,
                planning_ctx,
            )
        }
        LogicalPlan::Aggregate(aggregate) => {
            let input_exec = plan_grouped_output(
                planner,
                aggregate.input.as_ref(),
                physical_inputs,
                session_state,
                planning_ctx,
            )?;
            plan_grouped_aggregate(
                planner,
                aggregate,
                input_exec,
                session_state,
                planning_ctx,
            )
        }
        other => Err(DataFusionError::Internal(format!(
            "unexpected logical node in grouped MATCH_RECOGNIZE output: {}",
            other.display()
        ))),
    }
}

fn plan_grouped_projection(
    planner: &dyn PhysicalPlanner,
    projection: &Projection,
    input_exec: Arc<dyn ExecutionPlan>,
    session_state: &dyn Session,
    planning_ctx: &PhysicalPlanningContext,
) -> Result<Arc<dyn ExecutionPlan>> {
    let input_logical_schema = projection.input.schema();
    let input_physical_schema = input_exec.schema();
    let proj_exprs = projection
        .expr
        .iter()
        .map(|e| {
            let alias = if let Expr::Column(column) = e
                && let Ok(idx) = input_logical_schema.index_of_column(column)
            {
                input_physical_schema.field(idx).name().to_string()
            } else {
                physical_name(e)?
            };
            let expr = planner.create_physical_expr(
                e,
                input_logical_schema,
                session_state,
                planning_ctx,
            )?;
            Ok(ProjectionExpr { expr, alias })
        })
        .collect::<Result<Vec<_>>>()?;

    Ok(Arc::new(ProjectionExec::try_new_with_schema_metadata(
        proj_exprs,
        input_exec,
        projection.schema.as_arrow(),
    )?))
}

fn plan_grouped_aggregate(
    planner: &dyn PhysicalPlanner,
    aggregate: &Aggregate,
    input_exec: Arc<dyn ExecutionPlan>,
    session_state: &dyn Session,
    planning_ctx: &PhysicalPlanningContext,
) -> Result<Arc<dyn ExecutionPlan>> {
    let logical_input_schema = aggregate.input.schema();
    let physical_input_schema = input_exec.schema();
    let groups = PhysicalGroupBy::new_single(
        aggregate
            .group_expr
            .iter()
            .map(|e| {
                Ok((
                    planner.create_physical_expr(
                        e,
                        logical_input_schema,
                        session_state,
                        planning_ctx,
                    )?,
                    physical_name(e)?,
                ))
            })
            .collect::<Result<Vec<_>>>()?,
    );

    let execution_props = session_state.execution_props();
    let mut aggregates = Vec::with_capacity(aggregate.aggr_expr.len());
    let mut filters = Vec::with_capacity(aggregate.aggr_expr.len());
    for e in &aggregate.aggr_expr {
        let lowered = LoweredAggregateBuilder::new(
            e,
            logical_input_schema,
            physical_input_schema.as_ref(),
            execution_props,
            planning_ctx,
        )
        .build()?;
        aggregates.push(lowered.aggregate);
        filters.push(lowered.filter);
    }

    let next_partition_mode = if !groups.is_empty()
        && session_state.config().target_partitions() > 1
        && session_state.config().repartition_aggregations()
    {
        AggregateMode::FinalPartitioned
    } else {
        AggregateMode::Final
    };
    let initial_aggr = Arc::new(AggregateExec::try_new(
        AggregateMode::Partial,
        groups,
        aggregates,
        filters.clone(),
        input_exec,
        Arc::clone(&physical_input_schema),
    )?);
    let updated_aggregates = initial_aggr.aggr_expr().to_vec();
    let final_grouping_set = initial_aggr.group_expr().as_final();

    Ok(Arc::new(AggregateExec::try_new(
        next_partition_mode,
        final_grouping_set,
        updated_aggregates,
        filters,
        initial_aggr,
        physical_input_schema,
    )?))
}

impl fmt::Display for MatchRecognizeQueryPlanner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MatchRecognizeQueryPlanner")
    }
}

struct AggregateCseInput<'a> {
    matcher: &'a MatchRecognize,
    cse: Option<(&'a datafusion::common::DFSchema, Vec<Expr>)>,
}

/// Strip an optional DataFusion CSE projection sitting between a ONE ROW
/// `Aggregate` and `MatchRecognize` when it only forwards matcher columns and
/// standard selected-row filter subexpressions (`selected_row_filter_expr`,
/// `valid_match_row_expr`, or `is_matched_expr`).
fn unwrap_aggregate_cse_input(input: &LogicalPlan) -> Option<AggregateCseInput<'_>> {
    match input {
        LogicalPlan::Extension(extension) => {
            let matcher = extension.node.as_any().downcast_ref::<MatchRecognize>()?;
            Some(AggregateCseInput { matcher, cse: None })
        }
        LogicalPlan::Projection(cse) => {
            let LogicalPlan::Extension(extension) = cse.input.as_ref() else {
                return None;
            };
            let matcher = extension.node.as_any().downcast_ref::<MatchRecognize>()?;
            let is_matched = is_matched_expr();
            let valid_row = valid_match_row_expr();
            let selected_row = selected_row_filter_expr();
            let mut subst = Vec::with_capacity(cse.expr.len());
            for expr in &cse.expr {
                match expr {
                    Expr::Column(c) => {
                        matcher.schema().maybe_index_of_column(c)?;
                        subst.push(Expr::Column(c.clone()));
                    }
                    Expr::Alias(alias) if alias.relation.is_none() => {
                        let inner = alias.expr.as_ref();
                        if let Expr::Column(c) = inner {
                            matcher.schema().maybe_index_of_column(c)?;
                            subst.push(Expr::Column(c.clone()));
                        } else if inner == &selected_row
                            || inner == &valid_row
                            || inner == &is_matched
                        {
                            subst.push(inner.clone());
                        } else {
                            return None;
                        }
                    }
                    _ => return None,
                }
            }
            Some(AggregateCseInput {
                matcher,
                cse: Some((cse.schema.as_ref(), subst)),
            })
        }
        _ => None,
    }
}

fn inline_cse_expr(
    expr: &Expr,
    cse: Option<(&datafusion::common::DFSchema, &[Expr])>,
) -> Result<Option<Expr>> {
    let Some((cse_schema, subst)) = cse else {
        return Ok(Some(expr.clone()));
    };
    let mut valid = true;
    let rewritten = expr
        .clone()
        .transform_up(|node| {
            let Expr::Column(ref c) = node else {
                return Ok(Transformed::no(node));
            };
            let Some(idx) = cse_schema.maybe_index_of_column(c) else {
                valid = false;
                return Ok(Transformed::no(node));
            };
            Ok(Transformed::yes(subst[idx].clone()))
        })?
        .data;
    Ok(valid.then_some(rewritten))
}

/// Recognize the general ONE ROW finalizer after DataFusion's logical optimizer
/// has pruned unused measures. When all surviving aggregates (including zero)
/// qualify for native direct-summary finalization, fold the `Aggregate` directly
/// into `LogicalMatchOutput::SelectedSummaries` so execution skips per-match
/// row materialization and downstream grouping.
fn fold_one_row_aggregate(plan: &LogicalPlan) -> Result<Option<LogicalPlan>> {
    let LogicalPlan::Projection(projection) = plan else {
        return Ok(None);
    };
    let LogicalPlan::Aggregate(group) = projection.input.as_ref() else {
        return Ok(None);
    };
    let Some(AggregateCseInput { matcher, cse }) =
        unwrap_aggregate_cse_input(group.input.as_ref())
    else {
        return Ok(None);
    };
    let cse_ref = cse.as_ref().map(|(s, v)| (*s, v.as_slice()));
    let Some(bound_source) = matcher.bound_source() else {
        return Ok(None);
    };
    let program = matcher.program();
    let mut group_exprs = Vec::with_capacity(group.group_expr.len());
    for g in &group.group_expr {
        let Some(inlined) = inline_cse_expr(g, cse_ref)? else {
            return Ok(None);
        };
        group_exprs.push(inlined);
    }
    let Some((match_number, keys)) = group_exprs.split_last() else {
        return Ok(None);
    };
    if !matches!(
        bound_source
            .canonical_spec()
            .as_spec()
            .source_rows_per_match,
        RowsPerMatch::OneRow
    ) || program.rows_per_match() != &RowsPerMatch::AllRows(EmptyMatchesMode::Show)
        || keys != program.partition_by()
        || match_number != &col(MatchMetadataColumn::MatchNumber.as_ref())
    {
        return Ok(None);
    }
    // Visible partition columns must retain their grouping representation,
    // including signed zero in nested floating keys.
    if !projection.expr.is_empty()
        && program.has_float_partition_keys(matcher.input().schema())?
    {
        return Ok(None);
    }

    let private_schema = matcher.schema();
    let input_spec = program.output_spec();
    let input_schema = matcher.input().schema();
    let mut summaries = Vec::with_capacity(group.aggr_expr.len());
    let mut summary_names = Vec::with_capacity(group.aggr_expr.len());

    for (aggr_idx, aggr_expr) in group.aggr_expr.iter().enumerate() {
        let inner = match aggr_expr {
            Expr::Alias(alias) => alias.expr.as_ref(),
            other => other,
        };
        let Some(inlined_inner) = inline_cse_expr(inner, cse_ref)? else {
            return Ok(None);
        };
        let Expr::AggregateFunction(aggregate) = inlined_inner else {
            return Ok(None);
        };
        let (_, inferred_field) = Expr::AggregateFunction(aggregate.clone())
            .to_field(private_schema.as_ref())?;
        let group_field = group.schema.field(group.group_expr.len() + aggr_idx);
        if inferred_field.data_type() != group_field.data_type()
            || inferred_field.is_nullable() != group_field.is_nullable()
            || inferred_field.metadata() != group_field.metadata()
        {
            return Ok(None);
        }
        let field = MatchSummaryField::new(aggr_idx, inferred_field);
        let summary = LogicalSelectedMatchSummary::new(field, aggregate);
        if !summary.qualifies_for_direct(
            program,
            input_spec,
            private_schema.as_ref(),
            input_schema.as_ref(),
            true,
        ) {
            return Ok(None);
        }
        let name = summary.column_name();
        if input_schema.has_column_with_unqualified_name(&name)
            || private_schema.has_column_with_unqualified_name(&name)
        {
            return Ok(None);
        }
        summary_names.push(name);
        summaries.push(summary);
    }

    let mut visible_columns = Vec::new();
    let mut needs_match_number = false;
    let mut rewritten_exprs = Vec::with_capacity(projection.expr.len());

    for (proj_idx, expr) in projection.expr.iter().enumerate() {
        let has_subquery = expr.exists(|node| {
            Ok(matches!(
                node,
                Expr::OuterReferenceColumn(..)
                    | Expr::ScalarSubquery(_)
                    | Expr::SetComparison(_)
                    | Expr::Exists(_)
                    | Expr::InSubquery(_)
            ))
        })?;
        if has_subquery {
            return Ok(None);
        }

        let mut valid = true;
        let rewritten = expr
            .clone()
            .transform_up(|node| {
                let Expr::Column(ref column) = node else {
                    return Ok(Transformed::no(node));
                };
                let Some(col_idx) = group.schema.maybe_index_of_column(column) else {
                    valid = false;
                    return Ok(Transformed::no(node));
                };
                if col_idx < keys.len() {
                    let Expr::Column(key_col) = &keys[col_idx] else {
                        valid = false;
                        return Ok(Transformed::no(node));
                    };
                    let Some(input_idx) = input_schema.maybe_index_of_column(key_col)
                    else {
                        valid = false;
                        return Ok(Transformed::no(node));
                    };
                    visible_columns.push(input_idx);
                    let (qual, field) = input_schema.qualified_field(input_idx);
                    let resolved = Column::new(qual.cloned(), field.name());
                    if resolved != *column {
                        return Ok(Transformed::yes(Expr::Column(resolved)));
                    }
                    Ok(Transformed::no(node))
                } else if col_idx == keys.len() {
                    needs_match_number = true;
                    let mn = col(MatchMetadataColumn::MatchNumber.as_ref());
                    if node != mn {
                        return Ok(Transformed::yes(mn));
                    }
                    Ok(Transformed::no(node))
                } else {
                    let aggr_idx = col_idx - group.group_expr.len();
                    Ok(Transformed::yes(col(&summary_names[aggr_idx])))
                }
            })?
            .data;
        if !valid {
            return Ok(None);
        }
        let (orig_qual, orig_field) = projection.schema.qualified_field(proj_idx);
        let rewritten = if rewritten.qualified_name()
            != (orig_qual.cloned(), orig_field.name().clone())
        {
            rewritten.alias_qualified(orig_qual.cloned(), orig_field.name())
        } else {
            rewritten
        };
        rewritten_exprs.push(rewritten);
    }

    visible_columns.sort_unstable();
    visible_columns.dedup();
    let visible_metadata = if needs_match_number {
        vec![MatchMetadataColumn::MatchNumber]
    } else {
        vec![]
    };
    let visible = MatchRecognizeOutputSpec::with_validated_navigation_offsets(
        visible_columns,
        visible_metadata,
        vec![],
        input_spec.navigation_offsets(),
    );
    let private_spec = if summaries.is_empty() {
        MatchRecognizeOutputSpec::with_validated_navigation_offsets(
            vec![],
            vec![],
            vec![],
            input_spec.navigation_offsets(),
        )
    } else {
        input_spec.clone()
    };
    let rebuilt_matcher = matcher.rebuild_with_output(
        LogicalMatchOutput::selected_summaries(visible, private_spec, summaries),
    )?;
    for (proj_idx, expr) in rewritten_exprs.iter().enumerate() {
        let Ok((actual_qual, actual_field)) =
            expr.to_field(rebuilt_matcher.schema().as_ref())
        else {
            return Ok(None);
        };
        let (expected_qual, expected_field) = projection.schema.qualified_field(proj_idx);
        if actual_qual.as_ref() != expected_qual
            || actual_field.name() != expected_field.name()
            || actual_field.data_type() != expected_field.data_type()
            || actual_field.is_nullable() != expected_field.is_nullable()
            || actual_field.metadata() != expected_field.metadata()
        {
            return Ok(None);
        }
    }
    let mut projection = projection.clone();
    // Retain the parent's aliases, column order, and schema metadata.
    projection.expr = rewritten_exprs;
    projection.input = Arc::new(LogicalPlan::Extension(Extension {
        node: Arc::new(rebuilt_matcher),
    }));
    Ok(Some(LogicalPlan::Projection(projection)))
}

fn finalize_match_output(
    plan: &LogicalPlan,
    parallel: bool,
) -> Result<Cow<'_, LogicalPlan>> {
    if !plan.exists(|node| {
        Ok(match node {
            LogicalPlan::Projection(p) => matches!(
                p.input.as_ref(),
                LogicalPlan::Aggregate(g)
                    if g.group_expr.last()
                        == Some(&col(MatchMetadataColumn::MatchNumber.as_ref()))
            ),
            _ => false,
        })
    })? {
        return Ok(Cow::Borrowed(plan));
    }

    let rewritten = plan.clone().transform_up(|node| {
        if let Some(folded) = fold_one_row_aggregate(&node)? {
            return Ok(Transformed::yes(folded));
        }
        if parallel
            && let LogicalPlan::Projection(p) = &node
            && let Some(grouped) = private_groups::project(p)?
        {
            return Ok(Transformed::yes(grouped));
        }
        Ok(Transformed::no(node))
    })?;
    Ok(Cow::Owned(rewritten.data))
}

#[async_trait]
impl QueryPlanner for MatchRecognizeQueryPlanner {
    async fn create_physical_plan(
        &self,
        logical_plan: &LogicalPlan,
        session_state: &dyn Session,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        // Specialize only the physical plan. The retained source and logical
        // plan remain available for Substrait export with their original measures.
        let config = session_state.config_options();
        let parallel = config.execution.target_partitions > 1
            && !config
                .extensions
                .get::<MatchRecognizeConfig>()
                .is_some_and(|mr| mr.diagnostics.disable_parallel_no_partition);
        let plan = finalize_match_output(logical_plan, parallel)?;
        let plan = super::running_window::wrap_cow(plan)?;
        self.default_planner
            .create_physical_plan(plan.as_ref(), session_state)
            .await
    }
}

pub(crate) fn plan_match_recognize_extension(
    planner: &dyn PhysicalPlanner,
    node: &dyn datafusion::logical_expr::UserDefinedLogicalNode,
    physical_inputs: &[Arc<dyn ExecutionPlan>],
    session_state: &dyn Session,
    planning_ctx: &PhysicalPlanningContext,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
    use private_groups::PhysicalMatchOutput;
    let (mr, private_chunk) =
        if let Some(inline) = node.as_any().downcast_ref::<PhysicalMatchOutput>() {
            (&inline.matcher, true)
        } else if let Some(mr) = node.as_any().downcast_ref::<MatchRecognize>() {
            (mr, false)
        } else {
            return Ok(None);
        };
    let mr_config = session_state
        .config_options()
        .extensions
        .get::<MatchRecognizeConfig>()
        .cloned()
        .unwrap_or_default();
    let mut binder =
        PhysicalMatchBinder::new(planner, session_state, planning_ctx, &mr_config);
    let bound = binder.bind(mr, physical_inputs)?;
    let policy = PlannedRuntimePolicy::new(
        &bound,
        mr_config.limits.pattern_compile_limits(),
        mr_config.diagnostics.disable_compact_paths,
    );
    let raw_float_groups = mr.bound_source().is_none()
        && mr.program().has_float_partition_keys(mr.input().schema())?;
    let halo_bound = bound.clone();
    let pattern_exec = MatchRecognizePatternExec::new(bound, policy)
        .with_raw_float_groups(raw_float_groups);
    // Static navigation belongs to the ordered input adapter. Bind it before
    // Halo qualification so neighbor requirements cannot be hidden upstream.
    // Stateful programs with upstream windows (for example localized
    // cross-symbol NEXT) check Halo first so windows stay before chunking.
    let static_input = pattern_exec
        .program()
        .user_symbol_programs()
        .all(|s| s.evaluator().mode() == crate::core::SymbolEvalMode::Static);
    let pattern_exec = if static_input {
        pattern_exec.with_match_aware_input(mr, true, &mut binder)?
    } else {
        pattern_exec
    };
    let policy = pattern_exec.policy();
    let unpartitioned = pattern_exec.partition_keys().is_empty();
    if !mr_config.diagnostics.disable_parallel_no_partition
        && let Some(qualification) = policy.parallel_qualification()
        && (unpartitioned
            || mr_config.scheduler.parallel_no_partition_min_rows_per_task > 0)
    {
        let configured_core_rows = NonZeroUsize::new(mr_config.scheduler.parallel_no_partition_min_rows_per_task)
            .ok_or_else(|| DataFusionError::Configuration(
                "match_recognize.scheduler.parallel_no_partition_min_rows_per_task must be greater than zero for physical halo execution".into()))?;
        let core_rows = NonZeroUsize::new(
            configured_core_rows
                .get()
                .max(qualification.max_match_len()),
        )
        .expect("positive halo extent");
        let workers = session_state.config_options().execution.target_partitions;
        let profitable = if unpartitioned {
            unpartitioned_halo_is_profitable(
                &pattern_exec,
                core_rows,
                workers,
                session_state,
            )
        } else {
            keyed_halo_is_profitable(&pattern_exec, core_rows, workers, session_state)
        };
        if profitable {
            // Halo appends private grouping columns to its transport schema.
            // Keep derived slots in that schema, and leave SQL windows before
            // chunking, instead of reusing the compact ordinary-input mapping.
            let pattern_exec = MatchRecognizePatternExec::new(halo_bound, policy)
                .with_raw_float_groups(raw_float_groups)
                .with_match_aware_input(mr, false, &mut binder)?;
            return Ok(Some(pattern_exec.into_halo_pipeline(
                core_rows,
                workers,
                qualification,
                private_chunk,
            )?));
        }
    }
    let pattern_exec = if static_input {
        pattern_exec
    } else {
        pattern_exec.with_match_aware_input(mr, true, &mut binder)?
    };
    let matcher: Arc<dyn ExecutionPlan> = Arc::new(pattern_exec);
    Ok(Some(if private_chunk {
        super::halo::project_group_chunk(matcher, None)?
    } else {
        matcher
    }))
}

/// Avoid exchange and merge when ordinary prefix processing is safe and there
/// is no useful matching work to distribute. Unknown counts keep Halo enabled.
fn unpartitioned_halo_is_profitable(
    matcher: &MatchRecognizePatternExec,
    core_rows: NonZeroUsize,
    workers: usize,
    session: &dyn Session,
) -> bool {
    if workers < 2 {
        return false;
    }
    let input = Arc::clone(matcher.children()[0]);
    if input.boundedness() != Boundedness::Bounded {
        return true;
    }
    let context = session
        .statistics_registry()
        .cloned()
        .map(StatisticsContext::new_with_registry)
        .unwrap_or_default();
    let Ok(statistics) = context.compute(input.as_ref(), &StatisticsArgs::new()) else {
        return true;
    };
    let datafusion::common::stats::Precision::Exact(rows) = statistics.num_rows else {
        return true;
    };
    // Qualification excludes empty matches. Use the physically pruned program
    // so a final chunk shorter than its minimum match contributes no starts.
    let min_rows = matcher.program().compiled_automaton().min_match_rows();
    let useful_starts = rows.saturating_sub(min_rows - 1);
    useful_starts > core_rows.get()
}

/// Split only clearly under-parallelized, already ordered keyed input. Statistics
/// are cost hints, not a proof of group sizes or a condition of correct execution.
fn keyed_halo_is_profitable(
    matcher: &MatchRecognizePatternExec,
    core_rows: NonZeroUsize,
    workers: usize,
    session: &dyn Session,
) -> bool {
    let keys = matcher.partition_keys();
    let input = Arc::clone(matcher.children()[0]);
    if keys.is_empty()
        || workers < 2
        || input.output_partitioning().partition_count() != 1
        || input.boundedness() != Boundedness::Bounded
        || !matcher
            .partition_by_sort_keys()
            .is_ok_and(|ordered| ordered.len() == keys.len())
    {
        return false;
    }
    // The first alternative requires all keys before ORDER BY. An ordering only
    // within each group is insufficient for a chunker reading one continuous stream.
    let requirements = matcher.required_input_ordering();
    let Some(requirement) = &requirements[0] else {
        return false;
    };
    if !input
        .equivalence_properties()
        .ordering_satisfy_requirement(requirement.first().iter().cloned())
        .unwrap_or(false)
    {
        return false;
    }
    let context = session
        .statistics_registry()
        .cloned()
        .map(StatisticsContext::new_with_registry)
        .unwrap_or_default();
    let Ok(statistics) = context.compute(input.as_ref(), &StatisticsArgs::new()) else {
        return false;
    };
    let Some(rows) = statistics.num_rows.get_value().copied() else {
        return false;
    };
    // Require two full chunks per worker to amortize exchange and merging.
    if rows / core_rows.get() / workers < 2 {
        return false;
    }
    // Composite keys need more parallel headroom to justify chunking and merging.
    let max_groups = workers / if keys.len() == 1 { 2 } else { 4 };
    // Exact column counts bound the combinations without assuming independence.
    // Inexact counts remain cost hints, not a bound on actual groups.
    let schema = input.schema();
    let mut groups = 1;
    for key in &keys {
        let Some(column) = key.downcast_ref::<PhysicalColumn>() else {
            return false;
        };
        let Some(key_stats) = statistics.column_statistics.get(column.index()) else {
            return false;
        };
        let Some(distinct) = key_stats.distinct_count.get_value().copied() else {
            return false;
        };
        let may_have_nulls = schema.field(column.index()).is_nullable()
            && !matches!(
                key_stats.null_count,
                datafusion::common::stats::Precision::Exact(0)
            );
        let column_groups = distinct.saturating_add(usize::from(may_have_nulls));
        // Reject before multiplying so even extreme estimates cannot overflow.
        if column_groups == 0 || column_groups > max_groups / groups {
            return false;
        }
        groups *= column_groups;
    }
    true
}

#[cfg(test)]
mod tests;

mod private_groups;