Skip to main content

datafusion_match_recognize/planning/logical/
logical_node.rs

1// Licensed under the Apache License, Version 2.0 (the
2// "License"); you may not use this file except in compliance
3// with the License.  You may obtain a copy of the License at
4//
5//   http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing,
8// software distributed under the License is distributed on an
9// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
10// KIND, either express or implied.  See the License for the
11// specific language governing permissions and limitations
12// under the License.
13//
14// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.
15
16use super::program::{
17    LogicalMatchOutput, LogicalMatchProgram, LogicalMatchProgramInput,
18    LogicalSymbolPredicate, effective_deferred_columns_for_program,
19};
20use super::{
21    ExecutableMatchProgramInput, LogicalManagedAggregate, LogicalSymbolId,
22    LogicalSymbolInput, ManagedAggregateInput, utils,
23};
24#[cfg(any(test, feature = "internal-bench"))]
25use crate::core::classifier_bits_col_name;
26use crate::core::{
27    EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeOutputSpec, MatchSummaryField,
28    RowsPerMatch,
29};
30use crate::planning::bound_expr_lowering::{LoweredSourceMatch, lower_bound_match_spec};
31use crate::planning::define::{MatchRecognizeRequirements, requirements_for_lowered};
32use crate::planning::hybrid_guard::build_logical_hybrid_guard;
33use crate::planning::logical::utils::{
34    ExprBindings, build_match_aware_schema, extend_required_indices_from_exprs,
35};
36use crate::planning::logical::{
37    ExtractionKind, sequence_sort_expr, valid_match_row_expr,
38};
39use crate::planning::measures::{aggregate_selected_rows, one_row_group_exprs};
40use crate::planning::source::{
41    BoundMatchSpec, CanonicalBoundMatchSpec, MatchRecognizePlanningCapabilities,
42    canonicalize_bound_match_spec,
43};
44use crate::planning::{MatchRecognizePlanningContext, NamedExpr};
45use datafusion::arrow::array::BinaryViewBuilder;
46use datafusion::arrow::datatypes::DataType;
47use datafusion::arrow::row::{RowConverter, SortField};
48use datafusion::common::float_semantics::has_float_leaf;
49use datafusion::common::tree_node::{Transformed, TransformedResult, TreeNode};
50use datafusion::common::{Column, DFSchema, DFSchemaRef, Result, plan_err};
51use datafusion::logical_expr::Extension;
52use datafusion::logical_expr::expr::Cast;
53use datafusion::logical_expr::{
54    ColumnarValue, Expr, ExprFunctionExt, ExprSchemable, LogicalPlan, Projection,
55    ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, Volatility, col, lit,
56};
57use std::cmp::Ordering;
58use std::collections::{BTreeSet, HashSet};
59use std::fmt;
60use std::hash::{Hash, Hasher};
61use std::sync::{Arc, LazyLock};
62
63/// DataFusion's logical-plan node for matching patterns in ordered rows.
64#[derive(Clone, Debug)]
65pub struct MatchRecognize {
66    input: Arc<LogicalPlan>,
67    schema: DFSchemaRef,
68    program: Arc<LogicalMatchProgram>,
69
70    /// Validated source request retained so an exporter can reproduce it exactly.
71    ///
72    /// Source lowering retains this request for later export. Optimizers and
73    /// tests may construct a node without it when they do not need to recover
74    /// the source request.
75    bound_source: Option<Arc<BoundMatchSource>>,
76
77    /// Original prepared input expressions, shared across optimizer rebuilds.
78    /// The match program references their columns; export still needs to prove
79    /// that a rewritten input computes the same values for those columns.
80    prepared_exprs: Arc<[NamedExpr]>,
81}
82
83/// The validated input, request, and enabled features needed to rebuild a
84/// source-level `MATCH_RECOGNIZE` operation.
85#[derive(Clone, Debug, PartialEq)]
86pub struct BoundMatchSource {
87    input: Arc<LogicalPlan>,
88    spec: CanonicalBoundMatchSpec,
89    capabilities: MatchRecognizePlanningCapabilities,
90    requirements: MatchRecognizeRequirements,
91}
92
93impl BoundMatchSource {
94    /// Validate and normalize a source request using its actual function context.
95    pub fn try_new(
96        context: &mut dyn MatchRecognizePlanningContext,
97        input: LogicalPlan,
98        spec: BoundMatchSpec,
99        capabilities: MatchRecognizePlanningCapabilities,
100    ) -> Result<Self> {
101        Ok(Self::try_new_and_lower(context, input, spec, capabilities)?.0)
102    }
103
104    pub(crate) fn try_new_and_lower(
105        context: &mut dyn MatchRecognizePlanningContext,
106        input: LogicalPlan,
107        spec: BoundMatchSpec,
108        capabilities: MatchRecognizePlanningCapabilities,
109    ) -> Result<(Self, LoweredSourceMatch)> {
110        let spec = canonicalize_bound_match_spec(input.schema(), spec, capabilities)?;
111        let lowered = lower_bound_match_spec(context, &input, &spec)?;
112        let requirements = requirements_for_lowered(&lowered.spec);
113        Ok((
114            Self {
115                input: Arc::new(input),
116                spec,
117                capabilities,
118                requirements,
119            },
120            lowered,
121        ))
122    }
123
124    /// Return the source-level input associated with this request.
125    pub fn input(&self) -> &LogicalPlan {
126        self.input.as_ref()
127    }
128
129    /// Return the canonical request retained for lowering and source export.
130    pub fn canonical_spec(&self) -> &CanonicalBoundMatchSpec {
131        &self.spec
132    }
133
134    /// Return the source features checked during canonicalization.
135    #[cfg(test)]
136    pub const fn capabilities(&self) -> MatchRecognizePlanningCapabilities {
137        self.capabilities
138    }
139
140    /// Normalized DEFINE requirements of the retained source before runtime pruning.
141    pub fn requirements(&self) -> &MatchRecognizeRequirements {
142        &self.requirements
143    }
144}
145
146impl PartialEq for MatchRecognize {
147    fn eq(&self, other: &Self) -> bool {
148        self.input == other.input
149            && self.schema == other.schema
150            && self.program == other.program
151            && self.prepared_exprs == other.prepared_exprs
152    }
153}
154
155impl Eq for MatchRecognize {}
156
157impl Hash for MatchRecognize {
158    fn hash<H: Hasher>(&self, state: &mut H) {
159        self.input.hash(state);
160        self.schema.hash(state);
161        self.program.hash(state);
162        self.prepared_exprs.hash(state);
163    }
164}
165
166// Logical ordering ignores the bound source request.
167impl PartialOrd for MatchRecognize {
168    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
169        macro_rules! cmp_value {
170            ($left:expr, $right:expr) => {
171                match $left.partial_cmp($right) {
172                    Some(Ordering::Equal) => {}
173                    cmp => return cmp,
174                }
175            };
176        }
177
178        cmp_value!(self.input, &other.input);
179        cmp_value!(self.program.partition_by(), other.program.partition_by());
180        cmp_value!(self.program.order_by(), other.program.order_by());
181        cmp_value!(self.program.after_skip(), other.program.after_skip());
182        cmp_value!(
183            self.program.rows_per_match(),
184            other.program.rows_per_match()
185        );
186        cmp_value!(self.program.pattern(), other.program.pattern());
187
188        self.eq(other).then_some(Ordering::Equal)
189    }
190}
191
192fn fmt_list(f: &mut fmt::Formatter, label: &str, list: &[String]) -> fmt::Result {
193    if !list.is_empty() {
194        write!(f, " {}=[{}]", label, list.join(", "))?;
195    }
196    Ok(())
197}
198
199impl fmt::Display for MatchRecognize {
200    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
201        write!(f, "MatchRecognize:")?;
202        let partition_strs: Vec<String> = self
203            .program
204            .partition_by()
205            .iter()
206            .map(|e| e.to_string())
207            .collect();
208        fmt_list(f, "partition_by", &partition_strs)?;
209
210        let order_strs: Vec<String> = self
211            .program
212            .order_by()
213            .iter()
214            .map(|e| e.to_string())
215            .collect();
216        fmt_list(f, "order_by", &order_strs)?;
217
218        write!(f, " after_skip=[{}]", self.program.after_skip())?;
219        write!(f, " pattern=[{}]", self.program.pattern())?;
220
221        if !self.program.symbols().is_empty() {
222            let names = self.program.symbol_names().collect::<Vec<_>>();
223            write!(f, " symbols=[{}]", names.join(","))?;
224        }
225
226        write!(f, " rows_per_match=[{}]", self.program.rows_per_match())?;
227
228        let define_strs: Vec<String> = self
229            .program
230            .static_defines()
231            .map(|ne| format!("{}: {}", ne.name, ne.expr.clone().unalias_nested().data))
232            .collect();
233        fmt_list(f, "defines", &define_strs)?;
234
235        format_candidate_defines(&self.program, f)?;
236
237        if !self.program.selected_match_summaries().is_empty() {
238            let summaries = self
239                .program
240                .selected_match_summaries()
241                .iter()
242                .map(|summary| {
243                    let display_expr =
244                        Expr::AggregateFunction(summary.aggregate().clone())
245                            .unalias_nested()
246                            .data;
247                    format!("{}: {}", summary.column_name(), display_expr)
248                })
249                .collect::<Vec<_>>();
250            fmt_list(f, "selected_summaries", &summaries)?;
251        }
252
253        if !self.program.output().is_empty() {
254            write!(
255                f,
256                " {}",
257                self.program
258                    .output()
259                    .display_with_df_schema(self.input.schema())
260            )?;
261        }
262        Ok(())
263    }
264}
265
266impl MatchRecognize {
267    /// Create a checked low-level node from a fully assembled match program.
268    ///
269    /// `program.output` selects either ordinary matcher rows with an explicit
270    /// rows-per-match mode or matcher-owned selected summaries. Every selected
271    /// summary pairs its stable typed field with the exact aggregate evaluated
272    /// over its private row selection.
273    ///
274    /// Source adapters and ordinary programmatic builders should use
275    /// [`crate::planning::plan_match_recognize_from_source`] instead. That complete-plan
276    /// entry point retains the bound source and adds final output planning.
277    /// Caller-supplied patterns accept greedy and reluctant quantifiers;
278    /// possessive variants are reserved for proven internal optimizations.
279    /// Program structure and static predicate dependencies are checked before
280    /// resolving static predicate types against the input schema.
281    #[cfg(any(test, feature = "internal-bench"))]
282    #[doc(hidden)]
283    pub fn try_new(
284        input: LogicalPlan,
285        program: LogicalMatchProgramInput,
286    ) -> Result<Self> {
287        validate_programmatic_input(input.schema(), &program)?;
288        Self::try_new_inner(Arc::new(input), program, None)
289    }
290
291    pub(crate) fn try_new_with_source(
292        input: LogicalPlan,
293        program: LogicalMatchProgramInput,
294        bound_source: Arc<BoundMatchSource>,
295    ) -> Result<Self> {
296        let expected = &bound_source.canonical_spec().as_spec().symbols;
297        let actual = program
298            .symbols
299            .iter()
300            .map(|symbol| symbol.name.as_str())
301            .collect::<Vec<_>>();
302        if actual.as_slice() != expected.as_slice() {
303            return datafusion::common::plan_err!(
304                "MATCH_RECOGNIZE logical symbol order differs from canonical source order"
305            );
306        }
307        Self::try_new_inner(Arc::new(input), program, Some(bound_source))
308    }
309
310    fn try_new_inner(
311        input: Arc<LogicalPlan>,
312        program: LogicalMatchProgramInput,
313        bound_source: Option<Arc<BoundMatchSource>>,
314    ) -> Result<Self> {
315        let mut program = LogicalMatchProgram::try_new(program)?;
316        for symbol in &mut program.symbols {
317            if let LogicalSymbolPredicate::Static { expr } = &mut symbol.predicate {
318                match expr.get_type(input.schema())? {
319                    DataType::Boolean => {}
320                    DataType::Null => {
321                        let inner = std::mem::replace(expr, lit(true));
322                        *expr = Expr::Cast(Cast::new(Box::new(inner), DataType::Boolean));
323                    }
324                    data_type => {
325                        return datafusion::common::plan_err!(
326                            "MATCH_RECOGNIZE static predicate for symbol '{}' must be Boolean, got {data_type}",
327                            symbol.name
328                        );
329                    }
330                }
331            }
332        }
333        Self::from_program(input, program, bound_source, Arc::default())
334    }
335
336    fn from_program(
337        input: Arc<LogicalPlan>,
338        program: LogicalMatchProgram,
339        bound_source: Option<Arc<BoundMatchSource>>,
340        prepared_exprs: Arc<[NamedExpr]>,
341    ) -> Result<Self> {
342        crate::planning::type_validation::validate_schema(input.schema())?;
343        validate_rebuilt_matcher_exprs(input.schema(), &program)?;
344        for symbol in program.symbols() {
345            if let Some(expr) = symbol.predicate().static_expr() {
346                crate::planning::type_validation::validate_retained_expr(
347                    expr,
348                    input.schema(),
349                )?;
350            }
351        }
352        validate_candidate_types(&program, input.schema())?;
353        let program = program.with_pruned_selected_summary_input(input.schema())?;
354        validate_selected_match_summaries(input.schema(), &program)?;
355        let program = Arc::new(program.with_matcher_input_slots(input.schema())?);
356        let schema = program.output().build_df_schema(input.schema())?;
357        crate::planning::type_validation::validate_schema(&schema)?;
358        Ok(Self {
359            input,
360            schema,
361            program,
362            bound_source,
363            prepared_exprs,
364        })
365    }
366
367    /// Rebuild the logical node from replacement input and expressions.
368    pub(crate) fn rebuild_with(
369        &self,
370        input: Arc<LogicalPlan>,
371        exprs: Vec<Expr>,
372        output: LogicalMatchOutput,
373    ) -> Result<Self> {
374        if input.schema() == self.input.schema()
375            && &output == self.program.output()
376            && exprs == self.expr_adapter().expressions()
377        {
378            let mut rebuilt = self.clone();
379            rebuilt.input = input;
380            return Ok(rebuilt);
381        }
382        let program = self.expr_adapter().rebuild(exprs, output)?;
383        Self::from_program(
384            input,
385            program,
386            self.bound_source.clone(),
387            Arc::clone(&self.prepared_exprs),
388        )
389    }
390
391    /// Rebuild the logical node while only changing its complete output
392    /// contract.
393    pub(crate) fn rebuild_with_output(&self, output: LogicalMatchOutput) -> Result<Self> {
394        self.rebuild_with(
395            Arc::clone(&self.input),
396            self.expr_adapter().expressions(),
397            output,
398        )
399    }
400
401    fn expr_adapter(&self) -> MatchRecognizeExprAdapter<'_> {
402        MatchRecognizeExprAdapter::new(self)
403    }
404
405    /// Prune the complete output contract to columns referenced by a parent
406    /// projection.
407    pub(crate) fn pruned_output_for_projection_exprs(
408        &self,
409        projection_exprs: &[Expr],
410    ) -> Option<LogicalMatchOutput> {
411        let required_indices =
412            utils::required_output_indices(&self.schema, projection_exprs);
413        self.program.output().prune(&required_indices)
414    }
415
416    /// Return the child logical plan.
417    pub fn input(&self) -> &LogicalPlan {
418        self.input.as_ref()
419    }
420
421    /// Return the node's derived output schema.
422    pub fn schema(&self) -> &DFSchemaRef {
423        &self.schema
424    }
425
426    /// Return the checked logical match program.
427    pub(crate) fn program(&self) -> &LogicalMatchProgram {
428        &self.program
429    }
430
431    /// Return source provenance when this node came from a source adapter.
432    pub(crate) fn bound_source(&self) -> Option<&BoundMatchSource> {
433        self.bound_source.as_deref()
434    }
435
436    pub(crate) fn with_prepared_exprs(mut self, expressions: Vec<NamedExpr>) -> Self {
437        self.prepared_exprs = expressions.into();
438        self
439    }
440
441    /// Return the original defining expression of a prepared input column.
442    /// Source exporters use it to reject changes hidden by projection merging.
443    #[cfg(feature = "substrait")]
444    pub(crate) fn prepared_expr(&self, name: &str) -> Option<&Expr> {
445        self.prepared_exprs
446            .iter()
447            .find(|expression| expression.name == name)
448            .map(|expression| &expression.expr)
449    }
450
451    /// Return the source form of a retained prepared input expression.
452    ///
453    /// Export rebases window keys to their source expressions.
454    #[cfg(feature = "substrait")]
455    pub(crate) fn prepared_source_expr(&self, name: &str) -> Option<&Expr> {
456        self.prepared_expr(name).map(|expr| {
457            crate::planning::phases::prepared_key_source(expr).unwrap_or(expr)
458        })
459    }
460}
461
462#[cfg(any(test, feature = "internal-bench"))]
463fn validate_programmatic_input(
464    schema: &DFSchema,
465    program: &LogicalMatchProgramInput,
466) -> Result<()> {
467    crate::planning::source::validate_source_pattern_quantifiers(&program.pattern)?;
468    for field in schema.fields() {
469        let name = field.name();
470        let is_metadata = MatchMetadataColumn::all()
471            .into_iter()
472            .any(|column| column.as_ref() == name);
473        let is_classifier = program
474            .symbols
475            .iter()
476            .any(|symbol| classifier_bits_col_name(&symbol.name) == *name);
477        let is_summary = program
478            .output
479            .summary_fields()
480            .any(|summary| summary.column_name() == *name);
481        if is_metadata || is_classifier || is_summary {
482            return datafusion::common::plan_err!(
483                "MATCH_RECOGNIZE programmatic input field '{name}' collides with a generated MATCH_RECOGNIZE column"
484            );
485        }
486    }
487    Ok(())
488}
489
490fn validate_rebuilt_matcher_exprs(
491    input_schema: &DFSchema,
492    program: &LogicalMatchProgram,
493) -> Result<()> {
494    for expr in program.partition_by() {
495        expr.get_type(input_schema)?;
496        crate::planning::type_validation::validate_expr(expr, input_schema)?;
497    }
498    for sort in program.order_by() {
499        sort.expr.get_type(input_schema)?;
500        crate::planning::type_validation::validate_expr(&sort.expr, input_schema)?;
501    }
502    Ok(())
503}
504
505fn validate_selected_match_summaries(
506    input_schema: &DFSchema,
507    program: &LogicalMatchProgram,
508) -> Result<()> {
509    let Some(input_spec) = program.selected_match_summary_input_spec() else {
510        return Ok(());
511    };
512    let summary_input_schema = input_spec.build_df_schema(input_schema)?;
513    for summary in program.selected_match_summaries() {
514        let expr = Expr::AggregateFunction(summary.aggregate().clone());
515        crate::planning::type_validation::validate_expr(&expr, &summary_input_schema)?;
516        let (_, inferred) = expr.to_field(summary_input_schema.as_ref())?;
517        let inferred = MatchSummaryField::new(summary.output_id(), inferred);
518        if &inferred != summary.field() {
519            return datafusion::common::plan_err!(
520                "MATCH_RECOGNIZE selected summary {} has output field {:?}, but its aggregate infers {:?}",
521                summary.output_id(),
522                summary.field().arrow_field(),
523                inferred.arrow_field()
524            );
525        }
526    }
527    Ok(())
528}
529
530fn validate_candidate_types(
531    program: &LogicalMatchProgram,
532    input_schema: &DFSchemaRef,
533) -> Result<()> {
534    let schema = build_match_aware_schema(
535        input_schema,
536        &program.symbol_names().map(str::to_owned).collect(),
537    )?;
538    for symbol in program.symbols() {
539        for expr in [
540            symbol.predicate().local_expr(),
541            symbol.predicate().deferred_expr(),
542        ]
543        .into_iter()
544        .flatten()
545        {
546            crate::planning::type_validation::validate_expr(expr, &schema)?;
547        }
548    }
549    for extraction in program.static_extractions() {
550        crate::planning::type_validation::validate_retained_expr(
551            extraction.expr(),
552            &schema,
553        )?;
554    }
555    for aggregate in program.managed_aggregates() {
556        crate::planning::type_validation::validate_retained_expr(
557            &Expr::AggregateFunction(aggregate.func().clone()),
558            &schema,
559        )?;
560    }
561    Ok(())
562}
563
564fn format_candidate_defines(
565    program: &LogicalMatchProgram,
566    f: &mut fmt::Formatter,
567) -> fmt::Result {
568    let static_extraction_strs: Vec<String> = program
569        .static_extractions()
570        .iter()
571        .map(|extraction| {
572            let kind_str = match extraction.kind() {
573                ExtractionKind::BooleanAnd => "and_bool",
574                ExtractionKind::BooleanOr => "or_bool",
575                ExtractionKind::Scalar => "scalar",
576            };
577            format!(
578                "{} ({}): {}",
579                extraction.column_name(),
580                kind_str,
581                extraction.expr().clone().unalias_nested().data
582            )
583        })
584        .collect();
585    fmt_list(f, "static_extractions", &static_extraction_strs)?;
586
587    let inc_define_strs: Vec<String> = program
588        .symbols()
589        .iter()
590        .filter_map(|symbol| {
591            let expr = symbol.predicate().local_expr()?;
592            Some(format!(
593                "{}: {}",
594                symbol.name(),
595                expr.clone().unalias_nested().data
596            ))
597        })
598        .collect();
599    fmt_list(f, "incremental_defines", &inc_define_strs)?;
600
601    let agg_strs: Vec<String> = program
602        .managed_aggregates()
603        .iter()
604        .map(|agg| {
605            let display_expr = Expr::AggregateFunction(agg.func().clone())
606                .unalias_nested()
607                .data;
608            format!("{}: {}", agg.column_name(), display_expr)
609        })
610        .collect();
611    fmt_list(f, "managed_aggregates", &agg_strs)?;
612
613    Ok(())
614}
615
616fn extend_required_inputs(
617    program: &LogicalMatchProgram,
618    input_schema: &DFSchemaRef,
619    required_input_indices: &mut HashSet<usize>,
620) {
621    extend_required_indices_from_exprs(
622        required_input_indices,
623        input_schema,
624        program.symbols().iter().flat_map(|symbol| {
625            let predicate = symbol.predicate();
626            predicate
627                .local_expr()
628                .into_iter()
629                .chain(predicate.deferred_expr())
630        }),
631    );
632    for agg in program.managed_aggregates() {
633        extend_required_indices_from_exprs(
634            required_input_indices,
635            input_schema,
636            agg.func().params.args.iter(),
637        );
638        extend_required_indices_from_exprs(
639            required_input_indices,
640            input_schema,
641            agg.func().params.order_by.iter().map(|sort| &sort.expr),
642        );
643    }
644}
645
646impl datafusion::logical_expr::UserDefinedLogicalNodeCore for MatchRecognize {
647    fn name(&self) -> &str {
648        "MatchRecognize"
649    }
650
651    fn inputs(&self) -> Vec<&LogicalPlan> {
652        vec![self.input()]
653    }
654
655    fn schema(&self) -> &DFSchemaRef {
656        self.schema()
657    }
658
659    fn expressions(&self) -> Vec<Expr> {
660        // Precomputed static `defines` and `static_extractions` are excluded —
661        // the child Projection consumes their column references to compute
662        // __mr_symbol_* columns, allowing OptimizeProjections to prune dead
663        // columns. Demanded static defines are included because the matcher
664        // evaluates them directly and relies on SimplifyExpressions.
665        self.expr_adapter().expressions()
666    }
667
668    fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {
669        write!(f, "{self}")
670    }
671
672    fn prevent_predicate_push_down_columns(&self) -> HashSet<String> {
673        let input_schema = self.input().schema();
674        let partition_fields = self
675            .program()
676            .partition_by()
677            .iter()
678            .filter_map(|expr| match expr {
679                Expr::Column(column) => input_schema
680                    .qualified_field_with_name(column.relation.as_ref(), &column.name)
681                    .ok()
682                    .map(|(qualifier, field)| (qualifier, field.name())),
683                _ => None,
684            })
685            .collect::<HashSet<_>>();
686        let passthrough = self.program().output_spec().passthrough_input_indices();
687
688        let mut protected = self
689            .schema()
690            .fields()
691            .iter()
692            .enumerate()
693            .filter(|(index, _)| {
694                passthrough.get(*index).is_none_or(|&input_index| {
695                    let (qualifier, field) = input_schema.qualified_field(input_index);
696                    !partition_fields.contains(&(qualifier, field.name()))
697                })
698            })
699            .map(|(_, field)| field.name().clone())
700            .collect::<HashSet<_>>();
701
702        // DataFusion checks only the name and moves the original predicate.
703        // A bare reference can bind differently when the child also has a
704        // hidden field of the same name.
705        let mut input_names = HashSet::new();
706        for field in input_schema.fields() {
707            if !input_names.insert(field.name()) {
708                protected.insert(field.name().clone());
709            }
710        }
711        protected
712    }
713
714    fn with_exprs_and_inputs(
715        &self,
716        exprs: Vec<Expr>,
717        inputs: Vec<LogicalPlan>,
718    ) -> Result<Self> {
719        if inputs.len() != 1 {
720            return datafusion::common::plan_err!(
721                "MatchRecognize expects 1 input, got {}",
722                inputs.len()
723            );
724        }
725
726        let new_child_schema = inputs[0].schema();
727        let new_output = self
728            .program()
729            .output()
730            .remap(self.input().schema(), new_child_schema);
731
732        // Non-demanded static defines and static extractions stay outside the
733        // rewrite adapter (their child Projection owns their expressions).
734        self.rebuild_with(Arc::new(inputs[0].clone()), exprs, new_output)
735    }
736
737    fn necessary_children_exprs(
738        &self,
739        output_columns: &[usize],
740    ) -> Option<Vec<Vec<usize>>> {
741        let program = self.program();
742        let input_schema = self.input().schema();
743        let passthrough_input_indices = program.output_spec().passthrough_input_indices();
744        let num_passthrough = passthrough_input_indices.len();
745
746        let mut required_input_indices = HashSet::new();
747
748        for &output_idx in output_columns {
749            if output_idx < num_passthrough {
750                let input_idx = passthrough_input_indices[output_idx];
751                required_input_indices.insert(input_idx);
752            }
753        }
754
755        for expr in program.partition_by() {
756            extend_required_indices_from_exprs(
757                &mut required_input_indices,
758                input_schema,
759                std::iter::once(expr),
760            );
761        }
762
763        for sort_expr in program.order_by() {
764            extend_required_indices_from_exprs(
765                &mut required_input_indices,
766                input_schema,
767                std::iter::once(&sort_expr.expr),
768            );
769        }
770
771        // Demanded static predicates read the raw leaves in the matcher; their
772        // child membership fields are placeholders and cannot keep those inputs live.
773        extend_required_indices_from_exprs(
774            &mut required_input_indices,
775            input_schema,
776            program
777                .symbols()
778                .iter()
779                .filter_map(crate::planning::logical::LogicalSymbol::demanded_expr),
780        );
781
782        // Keep every declared schema-edge slot. Static expressions themselves
783        // stay outside DataFusion's rewrite list because the child Projection
784        // owns their raw dependencies.
785        utils::extend_required_indices_from_names(
786            &mut required_input_indices,
787            input_schema,
788            program.matcher_input_slots().iter().map(|slot| {
789                program
790                    .internal_slot_name(slot.owner())
791                    .expect("validated internal slot belongs to its program")
792            }),
793        );
794
795        extend_required_inputs(program, input_schema, &mut required_input_indices);
796
797        // Selected summaries consume the already-pruned private ordinary matcher
798        // stream, so its passthrough indices already capture every raw child
799        // column they depend on (including qualifier-disambiguated duplicate
800        // column names).
801        if let Some(input_spec) = program.selected_match_summary_input_spec() {
802            required_input_indices
803                .extend(input_spec.passthrough_input_indices().iter().copied());
804        }
805
806        let mut main_input_result: Vec<usize> =
807            required_input_indices.into_iter().collect();
808        main_input_result.sort_unstable();
809        Some(vec![main_input_result])
810    }
811}
812
813impl MatchRecognize {
814    /// Expand an explicitly requested one-row boundary whose measures require
815    /// DataFusion aggregation. The boundary exposes the first selected row and
816    /// stable summary fields, including after a caller prunes or reorders them.
817    pub(crate) fn grouped_output_plan(&self) -> Result<Option<LogicalPlan>> {
818        let program = self.program();
819        let LogicalMatchOutput::SelectedSummaries {
820            spec,
821            input_spec,
822            summaries,
823        } = program.output()
824        else {
825            return Ok(None);
826        };
827        let input = self.input().schema();
828        let private = input_spec.build_df_schema(input)?;
829        let raw_float_key =
830            self.bound_source().is_none() && program.has_float_partition_keys(input)?;
831        if summaries.iter().all(|summary| {
832            summary.qualifies_for_direct(
833                program,
834                input_spec,
835                private.as_ref(),
836                input.as_ref(),
837                !raw_float_key,
838            )
839        }) {
840            return Ok(None);
841        }
842        // The private aggregate inputs and the visible representative can have
843        // independent projections. Include the grouping and sequence columns
844        // even when neither is exposed at the old boundary.
845        let mut columns = input_spec
846            .passthrough_input_indices()
847            .iter()
848            .chain(spec.passthrough_input_indices())
849            .copied()
850            .collect::<BTreeSet<_>>();
851        for key in program.partition_by() {
852            for column in key.column_refs() {
853                columns.insert(input.index_of_column(column)?);
854            }
855        }
856        let mut metadata = MatchMetadataColumn::public_output().to_vec();
857        for column in spec.metadata_columns() {
858            if !metadata.contains(column) {
859                metadata.push(*column);
860            }
861        }
862        let classifiers = spec
863            .classifier_bitset_symbols()
864            .iter()
865            .chain(input_spec.classifier_bitset_symbols())
866            .cloned()
867            .collect::<BTreeSet<_>>();
868        let row_spec = MatchRecognizeOutputSpec::with_validated_navigation_offsets(
869            columns.into_iter().collect(),
870            metadata,
871            classifiers.into_iter().collect(),
872            spec.navigation_offsets(),
873        );
874        let rows = self.rebuild_with_output(LogicalMatchOutput::rows(
875            RowsPerMatch::AllRows(EmptyMatchesMode::Show),
876            row_spec,
877        ))?;
878        let rows = LogicalPlan::Extension(Extension {
879            node: Arc::new(rows),
880        });
881        let mut bindings = ExprBindings::new(
882            rows.schema(),
883            self.schema().fields().iter().map(|f| f.name().as_str()),
884        );
885        let mut keys = one_row_group_exprs(program.partition_by());
886        for key in &mut keys {
887            *key = qualify_columns(key.clone(), rows.schema())?;
888        }
889        if raw_float_key {
890            // Without SQL's prepared key, the matcher uses Arrow total-order
891            // equality. DataFusion GROUP BY normalizes signed zeros and NaNs.
892            for key in &mut keys {
893                if has_float_leaf(&key.get_type(rows.schema())?) {
894                    *key = RAW_GROUP_KEY.call(vec![key.clone()]);
895                }
896            }
897        }
898        let mut groups = Vec::with_capacity(keys.len());
899        for key in keys {
900            let before = bindings.binding_count();
901            let bound = bindings.bind(key);
902            if bindings.binding_count() > before {
903                groups.push(bound);
904            }
905        }
906        let group_count = bindings.binding_count();
907        let visible = spec.build_df_schema(input)?;
908        let mut outputs = Vec::with_capacity(self.schema().fields().len());
909        for column in visible.columns() {
910            let value = Expr::Column(column.clone());
911            if value == col(MatchMetadataColumn::MatchNumber.as_ref()) {
912                outputs.push(value);
913            } else {
914                let first =
915                    datafusion::functions_aggregate::first_last::first_value_udaf()
916                        .call(vec![value])
917                        .order_by(vec![sequence_sort_expr()])
918                        .filter(valid_match_row_expr())
919                        .build()?;
920                outputs.push(
921                    Expr::Column(bindings.register_occurrence(first))
922                        .alias_qualified(column.relation, column.name),
923                );
924            }
925        }
926        for summary in summaries {
927            let aggregate = qualify_columns(
928                Expr::AggregateFunction(summary.aggregate().clone()),
929                &private,
930            )?;
931            outputs.push(
932                Expr::Column(bindings.register_occurrence(aggregate))
933                    .alias(summary.column_name()),
934            );
935        }
936        let aggregates = bindings.aliased_expressions_from(group_count).collect();
937        let grouped = aggregate_selected_rows(rows, groups, aggregates)?;
938        Ok(Some(LogicalPlan::Projection(
939            Projection::try_new_with_schema(
940                outputs,
941                Arc::new(grouped),
942                Arc::clone(self.schema()),
943            )?,
944        )))
945    }
946}
947
948/// Qualify column references against the schema in which they were validated so
949/// widening the row stream cannot make them ambiguous.
950fn qualify_columns(expr: Expr, schema: &DFSchema) -> Result<Expr> {
951    expr.transform_up(|node| {
952        if let Expr::Column(ref column) = node
953            && let Some(index) = schema.maybe_index_of_column(column)
954        {
955            let (qualifier, field) = schema.qualified_field(index);
956            let resolved = Column::new(qualifier.cloned(), field.name());
957            if resolved != *column {
958                return Ok(Transformed::yes(Expr::Column(resolved)));
959            }
960        }
961        Ok(Transformed::no(node))
962    })
963    .data()
964}
965
966// Used only for source-less programmatic nodes, which cannot be exported to Substrait.
967#[derive(Debug, PartialEq, Eq, Hash)]
968struct RawGroupKey;
969
970static RAW_GROUP_KEY: LazyLock<ScalarUDF> =
971    LazyLock::new(|| ScalarUDF::new_from_impl(RawGroupKey));
972static RAW_KEY_SIGNATURE: LazyLock<Signature> =
973    LazyLock::new(|| Signature::any(1, Volatility::Immutable));
974
975impl ScalarUDFImpl for RawGroupKey {
976    fn name(&self) -> &str {
977        "__mr_raw_group_key"
978    }
979    fn signature(&self) -> &Signature {
980        &RAW_KEY_SIGNATURE
981    }
982    fn return_type(&self, _: &[DataType]) -> Result<DataType> {
983        Ok(DataType::BinaryView)
984    }
985    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
986        let array = args.args[0].clone().into_array(args.number_rows)?;
987        let encoder = RowConverter::new(vec![SortField::new(array.data_type().clone())])?;
988        let rows = encoder.convert_columns(&[array])?;
989        let mut keys = BinaryViewBuilder::with_capacity(rows.num_rows());
990        for row in rows.iter() {
991            keys.try_append_value(row.as_ref())?;
992        }
993        Ok(ColumnarValue::Array(Arc::new(keys.finish())))
994    }
995}
996
997enum RewriteSlot<'a> {
998    Partition(usize, &'a Expr),
999    Order(usize, &'a Expr),
1000    Demanded(LogicalSymbolId, &'a Expr),
1001    Local(LogicalSymbolId, &'a Expr),
1002    Deferred(LogicalSymbolId, &'a Expr),
1003    Managed(&'a LogicalManagedAggregate),
1004}
1005impl RewriteSlot<'_> {
1006    fn expression(&self) -> Expr {
1007        match self {
1008            Self::Partition(_, expr)
1009            | Self::Order(_, expr)
1010            | Self::Demanded(_, expr)
1011            | Self::Local(_, expr)
1012            | Self::Deferred(_, expr) => (*expr).clone(),
1013            Self::Managed(aggregate) => Expr::AggregateFunction(aggregate.func().clone())
1014                .alias(aggregate.column_name()),
1015        }
1016    }
1017}
1018struct MatchRecognizeExprAdapter<'a>(&'a MatchRecognize);
1019impl<'a> MatchRecognizeExprAdapter<'a> {
1020    const fn new(node: &'a MatchRecognize) -> Self {
1021        Self(node)
1022    }
1023    fn slots(&self) -> Vec<RewriteSlot<'a>> {
1024        let program = self.0.program();
1025        let mut slots = Vec::new();
1026        slots.extend(
1027            program
1028                .partition_by()
1029                .iter()
1030                .enumerate()
1031                .map(|(index, expr)| RewriteSlot::Partition(index, expr)),
1032        );
1033        slots.extend(
1034            program
1035                .order_by()
1036                .iter()
1037                .enumerate()
1038                .map(|(index, order)| RewriteSlot::Order(index, &order.expr)),
1039        );
1040        for symbol in program.symbols() {
1041            if let Some(expr) = symbol.demanded_expr() {
1042                slots.push(RewriteSlot::Demanded(symbol.id(), expr));
1043            }
1044        }
1045        for symbol in program.symbols() {
1046            if let Some(expr) = symbol.predicate().local_expr() {
1047                slots.push(RewriteSlot::Local(symbol.id(), expr));
1048            }
1049        }
1050        for symbol in program.symbols() {
1051            if let Some(expr) = symbol.predicate().deferred_expr() {
1052                slots.push(RewriteSlot::Deferred(symbol.id(), expr));
1053            }
1054        }
1055        slots.extend(
1056            program
1057                .managed_aggregates()
1058                .iter()
1059                .map(RewriteSlot::Managed),
1060        );
1061        slots
1062    }
1063    pub(crate) fn expressions(&self) -> Vec<Expr> {
1064        self.slots().iter().map(RewriteSlot::expression).collect()
1065    }
1066    pub(crate) fn rebuild(
1067        &self,
1068        exprs: Vec<Expr>,
1069        output: LogicalMatchOutput,
1070    ) -> Result<LogicalMatchProgram> {
1071        let slots = self.slots();
1072        let expected = slots.len();
1073        if exprs.len() != expected {
1074            return plan_err!(
1075                "MatchRecognize expects {expected} expressions, got {}",
1076                exprs.len()
1077            );
1078        }
1079        let program = self.0.program();
1080        let mut partition_by = program.partition_by().to_vec();
1081        let mut order_by = program.order_by().to_vec();
1082        let mut demanded = vec![None; program.symbols().len()];
1083        let mut local = vec![None; program.symbols().len()];
1084        let mut deferred = vec![None; program.symbols().len()];
1085        let mut aggregates = program
1086            .managed_aggregates()
1087            .iter()
1088            .map(|aggregate| aggregate.to_input(program.symbols()))
1089            .collect::<Vec<_>>();
1090        for (slot, expr) in slots.into_iter().zip(exprs) {
1091            match slot {
1092                RewriteSlot::Partition(index, _) => partition_by[index] = expr,
1093                RewriteSlot::Order(index, _) => order_by[index].expr = expr,
1094                RewriteSlot::Demanded(id, _) => demanded[id.index()] = Some(expr),
1095                RewriteSlot::Local(id, _) => local[id.index()] = Some(expr),
1096                RewriteSlot::Deferred(id, _) => deferred[id.index()] = Some(expr),
1097                RewriteSlot::Managed(old) => {
1098                    rewrite_managed_aggregate(
1099                        old,
1100                        expr,
1101                        &mut aggregates[old.id().index()],
1102                    )?;
1103                }
1104            }
1105        }
1106        let symbols = program
1107            .symbols()
1108            .iter()
1109            .map(|symbol| match symbol.predicate() {
1110                LogicalSymbolPredicate::Static { .. }
1111                    if symbol.demanded_expr().is_some() =>
1112                {
1113                    LogicalSymbolInput::demanded(
1114                        symbol.name(),
1115                        demanded[symbol.id().index()]
1116                            .take()
1117                            .expect("complete demanded rewrite slot"),
1118                    )
1119                }
1120                LogicalSymbolPredicate::Static { expr } => {
1121                    LogicalSymbolInput::static_(symbol.name(), expr.clone())
1122                }
1123                LogicalSymbolPredicate::MatchAware(_) => {
1124                    let id = symbol.id();
1125                    let local = local[id.index()].take();
1126                    if let Some(history) = deferred[id.index()].take() {
1127                        // Simplification can remove every Deferred dependency from a
1128                        // Hybrid local guard. Keep the history predicate in that case.
1129                        let local = local.filter(|expr| {
1130                            let columns =
1131                                effective_deferred_columns_for_program(program, id);
1132                            build_logical_hybrid_guard(expr, &columns).contains_unknown()
1133                        });
1134                        LogicalSymbolInput::history(symbol.name(), history, local)
1135                    } else {
1136                        LogicalSymbolInput::incremental(
1137                            symbol.name(),
1138                            local.expect("complete local rewrite slot"),
1139                        )
1140                    }
1141                }
1142            })
1143            .collect();
1144        LogicalMatchProgram::try_new(LogicalMatchProgramInput {
1145            partition_by,
1146            order_by,
1147            after_skip: program.after_skip().clone(),
1148            pattern: program.pattern().clone(),
1149            symbols,
1150            match_aware: ExecutableMatchProgramInput::new(
1151                program
1152                    .static_extractions()
1153                    .iter()
1154                    .map(|extraction| extraction.to_input(program.symbols()))
1155                    .collect(),
1156                aggregates,
1157            ),
1158            output,
1159            symbol_relationships: program.symbol_relationships().clone(),
1160        })
1161    }
1162}
1163
1164fn rewrite_managed_aggregate(
1165    old: &LogicalManagedAggregate,
1166    expr: Expr,
1167    aggregate: &mut ManagedAggregateInput,
1168) -> Result<()> {
1169    let id = old.id().index();
1170    let expected_name = old.column_name();
1171    let Expr::Alias(alias) = expr else {
1172        return plan_err!(
1173            "MatchRecognize managed aggregate {id} requires the {expected_name} aggregate slot"
1174        );
1175    };
1176    let Expr::AggregateFunction(func) = *alias.expr else {
1177        return plan_err!(
1178            "MatchRecognize managed aggregate {id} requires an aggregate expression"
1179        );
1180    };
1181    if alias.relation.is_some() || alias.name != expected_name || alias.metadata.is_some()
1182    {
1183        return plan_err!(
1184            "MatchRecognize managed aggregate {id} requires the {expected_name} aggregate slot"
1185        );
1186    }
1187    aggregate.replace_func(func);
1188    Ok(())
1189}
1190
1191#[cfg(test)]
1192mod stateful_define_tests;
1193
1194#[cfg(test)]
1195mod logical_node_udf_core_tests {
1196    use super::MatchRecognize;
1197    use crate::core::{
1198        AfterMatchSkip, EmptyMatchesMode, MatchRecognizeOutputSpec, Pattern,
1199        RowsPerMatch, Symbol, symbol_col_name,
1200    };
1201    use crate::planning::logical::{
1202        LogicalMatchOutput, LogicalMatchProgramInput, LogicalSymbolInput,
1203    };
1204    use datafusion::arrow::datatypes::{DataType, Field, Metadata};
1205    use datafusion::common::{DFSchema, Result, TableReference};
1206    use datafusion::logical_expr::{
1207        Expr, Extension, Filter, LogicalPlan, LogicalPlanBuilder,
1208        UserDefinedLogicalNodeCore, Values, col, lit,
1209    };
1210    use datafusion::optimizer::push_down_filter::PushDownFilter;
1211    use datafusion::optimizer::{Optimizer, OptimizerContext};
1212    use std::sync::Arc;
1213
1214    fn qualified_passthrough_node(partition_by: Vec<Expr>) -> Result<MatchRecognize> {
1215        let left = TableReference::bare("lhs");
1216        let right = TableReference::bare("rhs");
1217        let price = Arc::new(Field::new("price", DataType::Int64, false));
1218        let symbol = symbol_col_name("A");
1219        let schema = Arc::new(DFSchema::new_with_metadata(
1220            vec![
1221                (Some(left.clone()), Arc::clone(&price)),
1222                (Some(right), price),
1223                (
1224                    None,
1225                    Arc::new(Field::new(&symbol, DataType::Boolean, false)),
1226                ),
1227                (
1228                    Some(left),
1229                    Arc::new(Field::new("market", DataType::Int64, false)),
1230                ),
1231            ],
1232            Metadata::new(),
1233        )?);
1234        let input = LogicalPlan::Values(Values {
1235            values: vec![
1236                vec![lit(1_i64), lit(0_i64), lit(true), lit(1_i64)],
1237                vec![lit(1_i64), lit(1_i64), lit(true), lit(1_i64)],
1238            ],
1239            schema,
1240        });
1241        let a = Pattern::Symbol(Symbol::Named("A".into()));
1242        MatchRecognize::try_new(
1243            input,
1244            LogicalMatchProgramInput {
1245                partition_by,
1246                order_by: vec![],
1247                after_skip: AfterMatchSkip::PastLastRow,
1248                pattern: Pattern::Concat(vec![a.clone(), a]),
1249                symbols: vec![LogicalSymbolInput::static_("A", lit(true))],
1250                match_aware: None,
1251                output: LogicalMatchOutput::rows(
1252                    RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
1253                    MatchRecognizeOutputSpec::new(vec![0, 1, 3], vec![], vec![]),
1254                ),
1255                symbol_relationships: Default::default(),
1256            },
1257        )
1258    }
1259
1260    #[test]
1261    fn child_projection_keeps_only_the_surviving_qualified_passthrough() -> Result<()> {
1262        let node = qualified_passthrough_node(vec![])?;
1263        assert_eq!(node.necessary_children_exprs(&[1]), Some(vec![vec![1, 2]]));
1264        let child = LogicalPlanBuilder::from(node.input().clone())
1265            .project([col("rhs.price"), col(symbol_col_name("A"))])?
1266            .build()?;
1267        let projected = node.with_exprs_and_inputs(node.expressions(), vec![child])?;
1268        assert_eq!(
1269            projected
1270                .program()
1271                .output_spec()
1272                .passthrough_input_indices(),
1273            [0]
1274        );
1275        assert_eq!(projected.schema().fields().len(), 1);
1276        assert_eq!(
1277            projected.schema().qualified_field(0).0,
1278            Some(&TableReference::bare("rhs"))
1279        );
1280        Ok(())
1281    }
1282
1283    #[test]
1284    fn predicate_pushdown_checks_every_qualified_output_with_the_same_name() -> Result<()>
1285    {
1286        let optimizer = Optimizer::with_rules(vec![Arc::new(PushDownFilter::new())]);
1287        let context = OptimizerContext::new();
1288        let node = qualified_passthrough_node(vec![col("lhs.price"), col("lhs.market")])?;
1289        let rhs_price = col("rhs.price").eq(lit(1_i64));
1290        let market = col("lhs.market").eq(lit(1_i64));
1291        let plan = LogicalPlanBuilder::from(LogicalPlan::Extension(Extension {
1292            node: Arc::new(node),
1293        }))
1294        .filter(rhs_price.clone().and(market.clone()))?
1295        .build()?;
1296
1297        // Filtering rhs.price before matching would leave too few rows for A A.
1298        let retained = optimizer.optimize(plan, &context, |_, _| {})?;
1299        let LogicalPlan::Filter(filter) = retained else {
1300            panic!("rhs.price filter must stay above MATCH_RECOGNIZE");
1301        };
1302        assert_eq!(filter.predicate, rhs_price);
1303        let LogicalPlan::Extension(extension) = filter.input.as_ref() else {
1304            panic!("expected MATCH_RECOGNIZE under the retained filter");
1305        };
1306        let LogicalPlan::Filter(pushed) = extension.node.inputs()[0] else {
1307            panic!("expected the distinct partition key's filter on the child");
1308        };
1309        assert_eq!(pushed.predicate, market);
1310
1311        let projected = qualified_passthrough_node(vec![col("rhs.price")])?
1312            .rebuild_with_output(LogicalMatchOutput::rows(
1313                RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
1314                MatchRecognizeOutputSpec::new(vec![1], vec![], vec![]),
1315            ))?;
1316        let bare_price = Filter::try_new(
1317            col("price").eq(lit(1_i64)),
1318            Arc::new(LogicalPlan::Extension(Extension {
1319                node: Arc::new(projected),
1320            })),
1321        )?;
1322        let retained =
1323            optimizer.optimize(LogicalPlan::Filter(bare_price), &context, |_, _| {})?;
1324        assert!(matches!(retained, LogicalPlan::Filter(_)));
1325        Ok(())
1326    }
1327}
1328
1329#[cfg(test)]
1330mod grouped_output_tests {
1331    use super::*;
1332    use crate::core::{AfterMatchSkip, MatchSummaryField, Pattern, Symbol};
1333    use crate::planning::expressions::test_support::prepare_symbol_fields;
1334    use crate::planning::logical::{
1335        LogicalMatchProgramInput, LogicalSelectedMatchSummary, LogicalSymbolInput,
1336    };
1337    use crate::planning::symbol_relationships::SymbolRelationships;
1338    use datafusion::functions_aggregate::sum::sum;
1339    use datafusion::logical_expr::{LogicalPlanBuilder, lit};
1340    use std::collections::HashSet;
1341
1342    #[test]
1343    fn grouped_output_qualifies_summary_columns_when_widening_row_schema() -> Result<()> {
1344        let left = LogicalPlanBuilder::empty(false)
1345            .project([lit(1_i64).alias("v")])?
1346            .alias("left")?
1347            .build()?;
1348        let right = LogicalPlanBuilder::empty(false)
1349            .project([lit(2_i64).alias("v")])?
1350            .alias("right")?
1351            .build()?;
1352        let input = prepare_symbol_fields(
1353            LogicalPlanBuilder::from(left).cross_join(right)?.build()?,
1354            ["A".to_string()],
1355        )?;
1356        let input_spec = MatchRecognizeOutputSpec::new(vec![0], vec![], vec![]);
1357        let visible_spec = MatchRecognizeOutputSpec::new(vec![1], vec![], vec![]);
1358        let private = input_spec.build_df_schema(input.schema())?;
1359        let Expr::AggregateFunction(aggregate) = sum(col("v")) else {
1360            unreachable!()
1361        };
1362        let (_, field) =
1363            Expr::AggregateFunction(aggregate.clone()).to_field(private.as_ref())?;
1364        let program = LogicalMatchProgramInput {
1365            partition_by: vec![col("right.v")],
1366            order_by: vec![],
1367            after_skip: AfterMatchSkip::PastLastRow,
1368            pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
1369            symbols: vec![LogicalSymbolInput::static_("A", lit(true))],
1370            match_aware: None,
1371            output: LogicalMatchOutput::selected_summaries(
1372                visible_spec,
1373                input_spec,
1374                vec![LogicalSelectedMatchSummary::new(
1375                    MatchSummaryField::new(0, field),
1376                    aggregate,
1377                )],
1378            ),
1379            symbol_relationships: SymbolRelationships::default(),
1380        };
1381        let node = MatchRecognize::try_new(input, program)?;
1382        let grouped = node
1383            .grouped_output_plan()?
1384            .expect("plain sum requires DataFusion grouped output");
1385        assert_eq!(grouped.schema(), node.schema());
1386        let LogicalPlan::Projection(projection) = &grouped else {
1387            panic!("expected outer projection, got {grouped:?}");
1388        };
1389        let LogicalPlan::Aggregate(aggregate) = projection.input.as_ref() else {
1390            panic!("expected grouped aggregate, got {:?}", projection.input);
1391        };
1392        let summary_expr = aggregate
1393            .aggr_expr
1394            .last()
1395            .expect("summary aggregate should be present");
1396        let expected_col = Column::new(Some("left"), "v");
1397        assert_eq!(summary_expr.column_refs(), HashSet::from([&expected_col]));
1398        Ok(())
1399    }
1400
1401    #[test]
1402    fn grouped_output_deduplicates_duplicate_partition_by_keys() -> Result<()> {
1403        let input = prepare_symbol_fields(
1404            LogicalPlanBuilder::empty(false)
1405                .project([lit(1_i64).alias("p"), lit(2_i64).alias("value")])?
1406                .alias("t")?
1407                .build()?,
1408            ["A".to_string()],
1409        )?;
1410        let input_spec = MatchRecognizeOutputSpec::new(vec![1], vec![], vec![]);
1411        let visible_spec = MatchRecognizeOutputSpec::new(vec![0], vec![], vec![]);
1412        let private = input_spec.build_df_schema(input.schema())?;
1413        let Expr::AggregateFunction(aggregate) = sum(col("t.value")) else {
1414            unreachable!()
1415        };
1416        let (_, field) =
1417            Expr::AggregateFunction(aggregate.clone()).to_field(private.as_ref())?;
1418        let program = LogicalMatchProgramInput {
1419            partition_by: vec![
1420                col("t.p"),
1421                col("p"),
1422                col("t.p") + lit(1_i64),
1423                col("p") + lit(1_i64),
1424            ],
1425            order_by: vec![],
1426            after_skip: AfterMatchSkip::PastLastRow,
1427            pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
1428            symbols: vec![LogicalSymbolInput::static_("A", lit(true))],
1429            match_aware: None,
1430            output: LogicalMatchOutput::selected_summaries(
1431                visible_spec,
1432                input_spec,
1433                vec![LogicalSelectedMatchSummary::new(
1434                    MatchSummaryField::new(0, field),
1435                    aggregate,
1436                )],
1437            ),
1438            symbol_relationships: SymbolRelationships::default(),
1439        };
1440        let node = MatchRecognize::try_new(input, program)?;
1441        let grouped = node
1442            .grouped_output_plan()?
1443            .expect("plain sum requires DataFusion grouped output");
1444        assert_eq!(grouped.schema(), node.schema());
1445        let LogicalPlan::Projection(projection) = &grouped else {
1446            panic!("expected outer projection, got {grouped:?}");
1447        };
1448        let LogicalPlan::Aggregate(aggregate) = projection.input.as_ref() else {
1449            panic!("expected grouped aggregate, got {:?}", projection.input);
1450        };
1451        assert_eq!(aggregate.group_expr.len(), 3);
1452        Ok(())
1453    }
1454
1455    #[test]
1456    fn grouped_output_expands_uncoerced_null_shift_summary_with_non_null_default()
1457    -> Result<()> {
1458        use crate::core::NavigationOffsets;
1459        use crate::functions::udaf::{mr_next_udaf, mr_prev_udaf};
1460        use crate::planning::logical::is_matched_expr;
1461        use datafusion::common::ScalarValue;
1462        use datafusion::logical_expr::expr::AggregateFunction;
1463
1464        let input = prepare_symbol_fields(
1465            LogicalPlanBuilder::empty(false)
1466                .project([
1467                    lit(ScalarValue::Null).alias("null_col"),
1468                    lit(10_i64).alias("int_col"),
1469                ])?
1470                .alias("t")?
1471                .build()?,
1472            ["A".to_string()],
1473        )?;
1474        let nav =
1475            NavigationOffsets::try_from_raw(1, 1).expect("valid navigation offsets");
1476        let input_spec = MatchRecognizeOutputSpec::new(
1477            vec![0, 1],
1478            vec![
1479                MatchMetadataColumn::Classifier,
1480                MatchMetadataColumn::MatchSequenceNumber,
1481            ],
1482            vec![],
1483        )
1484        .with_navigation_offsets(nav);
1485        let visible_spec = MatchRecognizeOutputSpec::new(vec![], vec![], vec![])
1486            .with_navigation_offsets(nav);
1487        let private = input_spec.build_df_schema(input.schema())?;
1488
1489        for func in [mr_prev_udaf(), mr_next_udaf()] {
1490            // Uncoerced DataType::Null column with non-null Int64 default:
1491            // NavigationAgg infers Int64, so direct edge gathering cannot read
1492            // the Null input column and grouped_output_plan must expand.
1493            let uncoerced = AggregateFunction::new_udf(
1494                Arc::clone(&func),
1495                vec![
1496                    col("t.null_col"),
1497                    lit(1_u64),
1498                    lit(42_i64),
1499                    is_matched_expr(),
1500                    is_matched_expr(),
1501                ],
1502                false,
1503                None,
1504                vec![sequence_sort_expr()],
1505                None,
1506            );
1507            let (_, inferred) =
1508                Expr::AggregateFunction(uncoerced.clone()).to_field(private.as_ref())?;
1509            assert_eq!(inferred.data_type(), &DataType::Int64);
1510            let summary = LogicalSelectedMatchSummary::new(
1511                MatchSummaryField::new(0, inferred),
1512                uncoerced,
1513            );
1514            assert!(summary.selected_path_summary().is_some());
1515            let program = LogicalMatchProgramInput {
1516                partition_by: vec![],
1517                order_by: vec![],
1518                after_skip: AfterMatchSkip::PastLastRow,
1519                pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
1520                symbols: vec![LogicalSymbolInput::static_("A", lit(true))],
1521                match_aware: None,
1522                output: LogicalMatchOutput::selected_summaries(
1523                    visible_spec.clone(),
1524                    input_spec.clone(),
1525                    vec![summary],
1526                ),
1527                symbol_relationships: SymbolRelationships::default(),
1528            };
1529            let node = MatchRecognize::try_new(input.clone(), program)?;
1530            let grouped = node.grouped_output_plan()?.expect(
1531                "uncoerced Null column with Int64 default must expand to grouped output",
1532            );
1533            assert_eq!(grouped.schema(), node.schema());
1534            let LogicalPlan::Projection(projection) = &grouped else {
1535                panic!("expected outer projection, got {grouped:?}");
1536            };
1537            assert!(matches!(
1538                projection.input.as_ref(),
1539                LogicalPlan::Aggregate(_)
1540            ));
1541
1542            // Matching Int64 column with Int64 default remains on the direct path.
1543            let compatible = AggregateFunction::new_udf(
1544                func,
1545                vec![
1546                    col("t.int_col"),
1547                    lit(1_u64),
1548                    lit(42_i64),
1549                    is_matched_expr(),
1550                    is_matched_expr(),
1551                ],
1552                false,
1553                None,
1554                vec![sequence_sort_expr()],
1555                None,
1556            );
1557            let (_, field) =
1558                Expr::AggregateFunction(compatible.clone()).to_field(private.as_ref())?;
1559            let program = LogicalMatchProgramInput {
1560                partition_by: vec![],
1561                order_by: vec![],
1562                after_skip: AfterMatchSkip::PastLastRow,
1563                pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
1564                symbols: vec![LogicalSymbolInput::static_("A", lit(true))],
1565                match_aware: None,
1566                output: LogicalMatchOutput::selected_summaries(
1567                    visible_spec.clone(),
1568                    input_spec.clone(),
1569                    vec![LogicalSelectedMatchSummary::new(
1570                        MatchSummaryField::new(0, field),
1571                        compatible,
1572                    )],
1573                ),
1574                symbol_relationships: SymbolRelationships::default(),
1575            };
1576            let node = MatchRecognize::try_new(input.clone(), program)?;
1577            assert!(
1578                node.grouped_output_plan()?.is_none(),
1579                "matching Int64 shift summary should stay on the direct path"
1580            );
1581        }
1582        Ok(())
1583    }
1584
1585    #[test]
1586    fn qualifies_for_direct_checks_edge_field_metadata_and_nullability() -> Result<()> {
1587        use crate::core::NavigationOffsets;
1588        use crate::functions::udaf::mr_prev_udaf;
1589        use crate::planning::logical::is_matched_expr;
1590        use datafusion::arrow::datatypes::Field;
1591        use datafusion::logical_expr::expr::AggregateFunction;
1592        use std::collections::HashMap;
1593
1594        let input = prepare_symbol_fields(
1595            LogicalPlanBuilder::empty(false)
1596                .project([lit(10_i64).alias("int_col")])?
1597                .alias("t")?
1598                .build()?,
1599            ["A".to_string()],
1600        )?;
1601        let nav =
1602            NavigationOffsets::try_from_raw(1, 0).expect("valid navigation offsets");
1603        let input_spec = MatchRecognizeOutputSpec::new(
1604            vec![0],
1605            vec![
1606                MatchMetadataColumn::Classifier,
1607                MatchMetadataColumn::MatchSequenceNumber,
1608            ],
1609            vec![],
1610        )
1611        .with_navigation_offsets(nav);
1612        let visible_spec = MatchRecognizeOutputSpec::new(vec![], vec![], vec![])
1613            .with_navigation_offsets(nav);
1614        let private = input_spec.build_df_schema(input.schema())?;
1615        let aggregate = AggregateFunction::new_udf(
1616            mr_prev_udaf(),
1617            vec![
1618                col("t.int_col"),
1619                lit(1_u64),
1620                lit(42_i64),
1621                is_matched_expr(),
1622                is_matched_expr(),
1623            ],
1624            false,
1625            None,
1626            vec![sequence_sort_expr()],
1627            None,
1628        );
1629        let (_, inferred) =
1630            Expr::AggregateFunction(aggregate.clone()).to_field(private.as_ref())?;
1631        let node = MatchRecognize::try_new(
1632            input.clone(),
1633            LogicalMatchProgramInput {
1634                partition_by: vec![],
1635                order_by: vec![],
1636                after_skip: AfterMatchSkip::PastLastRow,
1637                pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
1638                symbols: vec![LogicalSymbolInput::static_("A", lit(true))],
1639                match_aware: None,
1640                output: LogicalMatchOutput::selected_summaries(
1641                    visible_spec,
1642                    input_spec.clone(),
1643                    vec![LogicalSelectedMatchSummary::new(
1644                        MatchSummaryField::new(0, inferred),
1645                        aggregate.clone(),
1646                    )],
1647                ),
1648                symbol_relationships: SymbolRelationships::default(),
1649            },
1650        )?;
1651
1652        let mismatched_metadata = LogicalSelectedMatchSummary::new(
1653            MatchSummaryField::new(
1654                0,
1655                Arc::new(
1656                    Field::new("s", DataType::Int64, true)
1657                        .with_metadata(HashMap::from([("k".into(), "v".into())])),
1658                ),
1659            ),
1660            aggregate.clone(),
1661        );
1662        assert!(!mismatched_metadata.qualifies_for_direct(
1663            node.program(),
1664            &input_spec,
1665            private.as_ref(),
1666            input.schema().as_ref(),
1667            true,
1668        ));
1669
1670        let non_nullable = LogicalSelectedMatchSummary::new(
1671            MatchSummaryField::new(0, Arc::new(Field::new("s", DataType::Int64, false))),
1672            aggregate,
1673        );
1674        assert!(!non_nullable.qualifies_for_direct(
1675            node.program(),
1676            &input_spec,
1677            private.as_ref(),
1678            input.schema().as_ref(),
1679            true,
1680        ));
1681        Ok(())
1682    }
1683}