Skip to main content

datafusion_match_recognize/substrait/
consumer.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
16//! Imports a Substrait `MATCH_RECOGNIZE` relation into DataFusion planning.
17
18use super::decode::*;
19use super::schema::{output_type_matches, validate_output_schema};
20use super::*;
21use crate::core::{
22    MatchMetadataColumn, MatchRecognizeOutputSpec, MatchSummaryField,
23    classifier_bits_col_name, is_reserved_internal_column_name,
24};
25use crate::planning::can_have_nulls_outside_bitmap;
26use crate::planning::logical::{LogicalMatchOutput, LogicalSelectedMatchSummary};
27use datafusion::common::ScalarValue;
28use datafusion::common::tree_node::{Transformed, TreeNode};
29use datafusion::functions_aggregate::count::count_udaf;
30use datafusion::logical_expr::{
31    ExprSchemable, Projection, SortExpr, TableType, WindowFrameBound,
32};
33use datafusion_substrait::logical_plan::consumer::{
34    DefaultSubstraitLambdaConsumer, from_scalar_function, from_substrait_func_args,
35};
36use std::collections::BTreeMap;
37use std::ops::Range;
38
39/// Converts a complete Substrait plan containing this package's
40/// `MATCH_RECOGNIZE` extension relation into a DataFusion logical plan.
41///
42/// Ordinary relations are delegated to DataFusion's Substrait consumer. The
43/// supplied session state resolves tables and registered functions while this
44/// package decodes, validates, and plans matcher relations.
45///
46/// # Errors
47///
48/// Returns an error when extension declarations cannot be decoded, type
49/// variation extensions are present, ordinary plan traversal cannot resolve an
50/// input, or a matcher relation is malformed, unsupported, or cannot be
51/// planned with `state`.
52pub async fn from_substrait_plan_with_match_recognize(
53    state: &SessionState,
54    plan: &Plan,
55) -> Result<LogicalPlan> {
56    let extensions = Extensions::try_from(&plan.extensions)?;
57    if !extensions.type_variations.is_empty() {
58        return not_impl_err!("Type variation extensions are not supported");
59    }
60
61    let consumer = MatchRecognizeSubstraitConsumer::new(&extensions, state);
62    from_substrait_plan_with_consumer(&consumer, plan).await
63}
64
65/// Substrait consumer that recognizes this package's extension relation and
66/// delegates ordinary relations to DataFusion.
67///
68/// Most callers should use [`from_substrait_plan_with_match_recognize`]. This
69/// type supports integrations that need to drive or customize the surrounding
70/// Substrait traversal.
71pub struct MatchRecognizeSubstraitConsumer<'a> {
72    extensions: &'a Extensions,
73    state: &'a SessionState,
74    outer_schemas: RwLock<Vec<Arc<DFSchema>>>,
75    lambda_consumer: DefaultSubstraitLambdaConsumer,
76}
77
78impl<'a> MatchRecognizeSubstraitConsumer<'a> {
79    /// Create a consumer using the plan's decoded `extensions` and the
80    /// registries and catalog in `state`.
81    pub fn new(extensions: &'a Extensions, state: &'a SessionState) -> Self {
82        Self {
83            extensions,
84            state,
85            outer_schemas: RwLock::new(Vec::new()),
86            lambda_consumer: DefaultSubstraitLambdaConsumer::new(),
87        }
88    }
89}
90
91#[async_trait]
92impl SubstraitConsumer for MatchRecognizeSubstraitConsumer<'_> {
93    async fn resolve_table_ref(
94        &self,
95        table_ref: &TableReference,
96    ) -> Result<Option<Arc<dyn TableProvider>>> {
97        let table = table_ref.table().to_string();
98        let schema = self.state.schema_for_ref(table_ref.clone())?;
99        let table_provider = schema.table(&table).await?;
100        Ok(table_provider)
101    }
102
103    fn get_extensions(&self) -> &Extensions {
104        self.extensions
105    }
106
107    fn get_function_registry(&self) -> &impl FunctionRegistry {
108        self.state
109    }
110
111    fn push_outer_schema(&self, schema: Arc<DFSchema>) {
112        self.outer_schemas.write().unwrap().push(schema);
113    }
114
115    fn pop_outer_schema(&self) {
116        self.outer_schemas.write().unwrap().pop();
117    }
118
119    fn get_outer_schema(&self, steps_out: usize) -> Option<Arc<DFSchema>> {
120        let schemas = self.outer_schemas.read().unwrap();
121        schemas
122            .len()
123            .checked_sub(steps_out)
124            .and_then(|idx| schemas.get(idx).cloned())
125    }
126
127    fn push_lambda_parameters(
128        &self,
129        parameters: &[proto::Type],
130        input_schema: &DFSchema,
131    ) -> Result<Vec<String>> {
132        self.lambda_consumer
133            .push_lambda_parameters(self, parameters, input_schema)
134    }
135
136    fn pop_lambda_parameters(&self) {
137        self.lambda_consumer.pop_lambda_parameters();
138    }
139
140    fn lambda_variable(&self, steps_out: usize, field_idx: usize) -> Result<Expr> {
141        self.lambda_consumer.lambda_variable(steps_out, field_idx)
142    }
143
144    async fn consume_scalar_function(
145        &self,
146        function: &proto::expression::ScalarFunction,
147        input_schema: &DFSchema,
148    ) -> Result<Expr> {
149        if self
150            .extensions
151            .functions
152            .get(&function.function_reference)
153            .is_some_and(|name| name == BUILTIN_SUBSTRING_NAME)
154        {
155            if !matches!(function.arguments.len(), 2 | 3) {
156                return plan_err!(
157                    "MATCH_RECOGNIZE SUBSTRING expects two or three arguments"
158                );
159            }
160            let args =
161                from_substrait_func_args(self, &function.arguments, input_schema).await?;
162            return Ok(datafusion::functions::unicode::substr().call(args));
163        }
164        from_scalar_function(self, function, input_schema).await
165    }
166
167    async fn consume_window_function(
168        &self,
169        expr: &proto::expression::WindowFunction,
170        input_schema: &DFSchema,
171    ) -> Result<Expr> {
172        window::decode_window_function(self, expr, input_schema).await
173    }
174
175    async fn consume_extension_single(
176        &self,
177        rel: &ExtensionSingleRel,
178    ) -> Result<LogicalPlan> {
179        let detail = rel.detail.as_ref().ok_or_else(|| {
180            datafusion::common::DataFusionError::Plan(
181                "ExtensionSingleRel missing detail".to_string(),
182            )
183        })?;
184        if detail.type_url != MATCH_RECOGNIZE_TYPE_URL {
185            return plan_err!(
186                "MATCH_RECOGNIZE Substrait adapter rejected unknown ExtensionSingleRel type URL '{}'",
187                detail.type_url
188            );
189        }
190
191        if matches!(
192            rel.common
193                .as_ref()
194                .and_then(|common| common.emit_kind.as_ref()),
195            Some(EmitKind::Emit(_))
196        ) {
197            return plan_err!(
198                "MATCH_RECOGNIZE Substrait extension does not support ExtensionSingleRel.common.emit"
199            );
200        }
201
202        let input_rel = rel.input.as_ref().ok_or_else(|| {
203            datafusion::common::DataFusionError::Plan(
204                "MATCH_RECOGNIZE ExtensionSingleRel missing input".to_string(),
205            )
206        })?;
207        let input = self.consume_rel(input_rel).await?;
208        let (payload, capabilities, boundary) = decode_match_recognize_payload(detail)?;
209        let input = if boundary == MatchRecognizeBoundary::CompletePlan {
210            input
211        } else {
212            sanitize_semantic_node_input(input)?
213        };
214        let decoded = decode_match_recognize_detail_from_payload(
215            self,
216            payload,
217            capabilities,
218            boundary,
219            input.schema(),
220        )
221        .await?;
222
223        let mut planning_context = SubstraitPlanningContext { state: self.state };
224        validate_define_declaration(&mut planning_context, &input, &decoded)?;
225        let boundary = decoded.boundary;
226        let planned = match boundary {
227            MatchRecognizeBoundary::CompletePlan => {
228                plan_match_recognize_from_source_with_capabilities(
229                    &mut planning_context,
230                    input,
231                    decoded.spec,
232                    decoded.capabilities,
233                )?
234            }
235            MatchRecognizeBoundary::RowStreamNode => {
236                plan_match_recognize_node_from_source_with_capabilities(
237                    &mut planning_context,
238                    input,
239                    decoded.spec,
240                    decoded.capabilities,
241                )?
242            }
243            MatchRecognizeBoundary::OneRowNode => {
244                plan_match_recognize_native_one_row_node_from_source_with_capabilities(
245                    &mut planning_context,
246                    input,
247                    decoded.spec,
248                    decoded.capabilities,
249                )?
250            }
251        };
252        let expected = from_substrait_named_struct(self, &decoded.output_schema)?;
253        let expected_types = decoded
254            .output_schema
255            .r#struct
256            .as_ref()
257            .ok_or_else(|| {
258                datafusion::common::DataFusionError::Plan(
259                    "MATCH_RECOGNIZE output schema missing struct".to_string(),
260                )
261            })?
262            .types
263            .as_slice();
264        let planned = if boundary == MatchRecognizeBoundary::CompletePlan {
265            planned
266        } else {
267            align_semantic_output(
268                planned,
269                &expected,
270                expected_types,
271                &decoded.retained_passthrough_input_fields,
272                &decoded.prepared_output_fields,
273                &decoded.summary_output_fields,
274            )?
275        };
276        validate_output_schema(&planned, &expected, expected_types, boundary)?;
277        Ok(planned)
278    }
279
280    async fn consume_extension_leaf(
281        &self,
282        rel: &ExtensionLeafRel,
283    ) -> Result<LogicalPlan> {
284        let Some(detail) = rel.detail.as_ref() else {
285            return substrait_err!("Unexpected empty detail in ExtensionLeafRel");
286        };
287        plan_err!(
288            "MATCH_RECOGNIZE Substrait adapter rejected unsupported ExtensionLeafRel type URL '{}'",
289            detail.type_url
290        )
291    }
292
293    async fn consume_extension_multi(
294        &self,
295        rel: &ExtensionMultiRel,
296    ) -> Result<LogicalPlan> {
297        let Some(detail) = rel.detail.as_ref() else {
298            return substrait_err!("Unexpected empty detail in ExtensionMultiRel");
299        };
300        plan_err!(
301            "MATCH_RECOGNIZE Substrait adapter rejected unsupported ExtensionMultiRel type URL '{}'",
302            detail.type_url
303        )
304    }
305}
306
307struct PlannedSummary {
308    exact: DecodedSummaryAggregate,
309    folded: Option<DecodedSummaryAggregate>,
310    is_builtin_count: bool,
311    is_volatile: bool,
312}
313
314fn align_semantic_output(
315    plan: LogicalPlan,
316    expected: &DFSchema,
317    expected_types: &[proto::Type],
318    retained_input_fields: &[Column],
319    prepared_output_fields: &[(usize, Expr)],
320    summary_output_fields: &[(usize, DecodedSummaryAggregate)],
321) -> Result<LogicalPlan> {
322    let LogicalPlan::Extension(extension) = &plan else {
323        return plan_err!(
324            "MATCH_RECOGNIZE native semantic-node planning did not return an extension node"
325        );
326    };
327    let Some(node) = extension.node.as_any().downcast_ref::<MatchRecognize>() else {
328        return plan_err!(
329            "MATCH_RECOGNIZE native semantic-node planning returned an unexpected extension node"
330        );
331    };
332    let source_input = node
333        .bound_source()
334        .ok_or_else(|| {
335            datafusion::common::DataFusionError::Plan(
336                "MATCH_RECOGNIZE native semantic-node planning did not retain bound source"
337                    .to_string(),
338            )
339        })?
340        .input();
341    let source_schema = source_input.schema();
342
343    let full = node.program().output();
344    let spec = full.spec();
345    let passthrough = spec.passthrough_input_indices();
346    let actual = node.schema();
347    let metadata_start = passthrough.len();
348    let classifier_start = metadata_start + spec.metadata_columns().len();
349    let summary_start = classifier_start + spec.classifier_bitset_symbols().len();
350    let ordinary_source_positions = passthrough
351        .iter()
352        .enumerate()
353        .filter_map(|(position, &index)| {
354            let (qualifier, field) = node.input().schema().qualified_field(index);
355            source_schema
356                .qualified_field_from_column(&Column::new(
357                    qualifier.cloned(),
358                    field.name(),
359                ))
360                .is_ok()
361                .then_some(position)
362        })
363        .collect::<BTreeSet<_>>();
364    let mut retained = Vec::with_capacity(expected.fields().len());
365    let mut used = BTreeSet::new();
366    for column in retained_input_fields {
367        let input_index = node.input().schema().index_of_column(column)?;
368        let positions = passthrough
369            .iter()
370            .enumerate()
371            .filter(|(_, index)| **index == input_index)
372            .map(|(position, _)| position)
373            .collect::<Vec<_>>();
374        let [position] = positions.as_slice() else {
375            return plan_err!(
376                "MATCH_RECOGNIZE retained input column '{}' does not identify one passthrough output",
377                column
378            );
379        };
380        used.insert(*position);
381        retained.push(*position);
382    }
383    let mut prepared_windows = BTreeMap::new();
384    for (position, &index) in passthrough.iter().enumerate() {
385        if !ordinary_source_positions.contains(&position)
386            && let Some(expression) =
387                producer::prepared_window_expr(node, index, source_schema)?
388        {
389            prepared_windows
390                .insert(position, normalize_wire_expr(expression, source_schema)?);
391        }
392    }
393    let prepared_output_fields = prepared_output_fields
394        .iter()
395        .map(|(position, expression)| {
396            Ok((
397                *position,
398                normalize_wire_expr(expression.clone(), source_schema)?,
399            ))
400        })
401        .collect::<Result<BTreeMap<_, _>>>()?;
402    let symbols = node
403        .program()
404        .symbols()
405        .iter()
406        .map(|symbol| symbol.name().to_string())
407        .collect::<Vec<_>>();
408    let builtin_count = count_udaf();
409    let (planned_summaries, expected_summaries) = if !full
410        .selected_match_summaries()
411        .is_empty()
412        || !summary_output_fields.is_empty()
413    {
414        let summary_schema = summary_wire_decode_schema(source_schema, &symbols)?;
415        let planned_summaries = full
416            .selected_match_summaries()
417            .iter()
418            .map(|summary| {
419                let exact = planned_summary_identity(
420                    summary,
421                    node,
422                    source_schema,
423                    &summary_schema,
424                )?;
425                let is_builtin_count =
426                    Arc::ptr_eq(summary.aggregate().func.inner(), builtin_count.inner());
427                let folded = is_builtin_count
428                    .then(|| {
429                        folded_required_count_identity(&exact, source_input, &symbols)
430                    })
431                    .flatten();
432                let is_volatile =
433                    Expr::AggregateFunction(summary.aggregate().clone()).is_volatile();
434                Ok(PlannedSummary {
435                    exact,
436                    folded,
437                    is_builtin_count,
438                    is_volatile,
439                })
440            })
441            .collect::<Result<Vec<_>>>()?;
442        let expected_summaries = summary_output_fields
443            .iter()
444            .map(|(position, summary)| {
445                Ok((
446                    *position,
447                    normalize_decoded_summary(summary, &summary_schema)?,
448                ))
449            })
450            .collect::<Result<BTreeMap<_, _>>>()?;
451        (planned_summaries, expected_summaries)
452    } else {
453        (Vec::new(), BTreeMap::new())
454    };
455    let mut seen_non_volatile_summaries = Vec::new();
456    for (output_index, expected_field) in
457        expected.fields().iter().enumerate().skip(retained.len())
458    {
459        if let Some(expected_summary) = expected_summaries.get(&output_index) {
460            let mut exact_matches = Vec::new();
461            for (offset, planned) in planned_summaries.iter().enumerate() {
462                let position = summary_start + offset;
463                let field = actual.field(position);
464                if !used.contains(&position)
465                    && planned.exact == *expected_summary
466                    && field.is_nullable() == expected_field.is_nullable()
467                    && output_type_matches(
468                        field.data_type(),
469                        expected_field.data_type(),
470                        &expected_types[output_index],
471                    )?
472                {
473                    exact_matches.push(offset);
474                }
475            }
476            if exact_matches.len() > 1 {
477                let by_name = exact_matches
478                    .iter()
479                    .copied()
480                    .filter(|&offset| {
481                        actual.field(summary_start + offset).name()
482                            == expected_field.name()
483                    })
484                    .collect::<Vec<_>>();
485                exact_matches = if by_name.is_empty() {
486                    vec![exact_matches[0]]
487                } else {
488                    by_name
489                };
490            }
491            let (matched_offset, matched_exact) = match exact_matches.as_slice() {
492                [offset] => (*offset, true),
493                [] => {
494                    if seen_non_volatile_summaries.contains(&expected_summary) {
495                        return plan_err!(
496                            "MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
497                            expected_field.name()
498                        );
499                    }
500                    let expected_folded = folded_required_count_identity(
501                        expected_summary,
502                        source_input,
503                        &symbols,
504                    );
505                    let mut folded_matches = Vec::new();
506                    for (offset, planned) in planned_summaries.iter().enumerate() {
507                        let position = summary_start + offset;
508                        let field = actual.field(position);
509                        if !planned.is_volatile
510                            && planned.is_builtin_count
511                            && field.is_nullable() == expected_field.is_nullable()
512                            && output_type_matches(
513                                field.data_type(),
514                                expected_field.data_type(),
515                                &expected_types[output_index],
516                            )?
517                            && (expected_folded.as_ref() == Some(&planned.exact)
518                                || planned.folded.as_ref() == Some(expected_summary))
519                        {
520                            folded_matches.push(offset);
521                        }
522                    }
523                    let Some(&offset) = folded_matches.first() else {
524                        return plan_err!(
525                            "MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
526                            expected_field.name()
527                        );
528                    };
529                    (offset, false)
530                }
531                _ => {
532                    return plan_err!(
533                        "MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
534                        expected_field.name()
535                    );
536                }
537            };
538            let position = summary_start + matched_offset;
539            if matched_exact {
540                used.insert(position);
541            }
542            if !planned_summaries[matched_offset].is_volatile
543                && !seen_non_volatile_summaries.contains(&expected_summary)
544            {
545                seen_non_volatile_summaries.push(expected_summary);
546            }
547            retained.push(position);
548            continue;
549        }
550        // Prepared placeholders and LAG/LEAD outputs are not source ordinals.
551        // Window display names change with consumed aliases, so match the full
552        // defining expression. Other generated non-summary outputs retain unique names.
553        let prepared = prepared_output_fields.get(&output_index);
554        let mut positions = Vec::new();
555        for (position, field) in actual.fields().iter().enumerate().take(summary_start) {
556            if !ordinary_source_positions.contains(&position)
557                && !used.contains(&position)
558                && match prepared {
559                    Some(expression) => {
560                        prepared_windows.get(&position) == Some(expression)
561                    }
562                    None => {
563                        !prepared_windows.contains_key(&position)
564                            && field.name() == expected_field.name()
565                    }
566                }
567                && field.is_nullable() == expected_field.is_nullable()
568                && output_type_matches(
569                    field.data_type(),
570                    expected_field.data_type(),
571                    &expected_types[output_index],
572                )?
573            {
574                positions.push(position);
575            }
576        }
577        if positions.len() > 1
578            && let Some(expression) = prepared
579        {
580            if expression.is_volatile() {
581                // Equal volatile windows have separate, source-ordered aliases.
582                positions.retain(|&position| {
583                    actual.field(position).name() == expected_field.name()
584                });
585            } else {
586                // Distinct non-volatile ASTs that normalize to the same wire
587                // expression are semantically equivalent; prefer an exact alias
588                // match and otherwise consume the first unused slot.
589                let by_name = positions
590                    .iter()
591                    .copied()
592                    .filter(|&position| {
593                        actual.field(position).name() == expected_field.name()
594                    })
595                    .collect::<Vec<_>>();
596                positions = if by_name.is_empty() {
597                    vec![positions[0]]
598                } else {
599                    by_name
600                };
601            }
602        }
603        let [position] = positions.as_slice() else {
604            return plan_err!(
605                "MATCH_RECOGNIZE native semantic-node generated output field '{}' does not identify one unambiguous retained field",
606                expected_field.name()
607            );
608        };
609        used.insert(*position);
610        retained.push(*position);
611    }
612
613    let mut selected_passthrough = Vec::new();
614    let mut selected_metadata = Vec::new();
615    let mut selected_classifiers = Vec::new();
616    let mut selected_summaries = Vec::new();
617    let mut previous_group = 0;
618    for index in retained {
619        let group = if index < metadata_start {
620            selected_passthrough.push(passthrough[index]);
621            0
622        } else if index < classifier_start {
623            selected_metadata.push(spec.metadata_columns()[index - metadata_start]);
624            1
625        } else if index < summary_start {
626            selected_classifiers
627                .push(spec.classifier_bitset_symbols()[index - classifier_start].clone());
628            2
629        } else {
630            let summary = &full.selected_match_summaries()[index - summary_start];
631            let field = MatchSummaryField::new(
632                selected_summaries.len(),
633                summary.field().arrow_field(),
634            );
635            selected_summaries.push(LogicalSelectedMatchSummary::new(
636                field,
637                summary.aggregate().clone(),
638            ));
639            3
640        };
641        if group < previous_group {
642            return plan_err!(
643                "MATCH_RECOGNIZE native semantic-node output fields are not in matcher output order"
644            );
645        }
646        previous_group = group;
647    }
648    let selected_spec = MatchRecognizeOutputSpec::with_validated_navigation_offsets(
649        selected_passthrough,
650        selected_metadata,
651        selected_classifiers,
652        spec.navigation_offsets(),
653    );
654    let output = match full {
655        LogicalMatchOutput::SelectedSummaries { input_spec, .. } => {
656            LogicalMatchOutput::selected_summaries(
657                selected_spec,
658                input_spec.clone(),
659                selected_summaries,
660            )
661        }
662        LogicalMatchOutput::Rows { rows_per_match, .. } => {
663            LogicalMatchOutput::rows(rows_per_match.clone(), selected_spec)
664        }
665    };
666    let aligned = node.rebuild_with_output(output)?;
667    if let Some(grouped) = aligned.grouped_output_plan()? {
668        return Ok(grouped);
669    }
670    Ok(LogicalPlan::Extension(Extension {
671        node: Arc::new(aligned),
672    }))
673}
674
675struct SubstraitPlanningContext<'a> {
676    state: &'a SessionState,
677}
678
679impl MatchRecognizePlanningContext for SubstraitPlanningContext<'_> {
680    fn options(&self) -> &datafusion::common::config::ConfigOptions {
681        self.state.config_options()
682    }
683
684    fn scalar_udf(&self, name: &str) -> Option<Arc<ScalarUDF>> {
685        self.state.udf(name).ok()
686    }
687
688    fn aggregate_udf(&self, name: &str) -> Option<Arc<AggregateUDF>> {
689        self.state
690            .udaf(name)
691            .ok()
692            .or_else(|| self.options().aggregate_udf(name))
693    }
694}
695
696/// Output contract represented by one decoded `MATCH_RECOGNIZE` relation.
697#[derive(Clone, Copy, Debug, PartialEq, Eq)]
698pub enum MatchRecognizeBoundary {
699    /// Complete output plan, including its projections or final aggregation.
700    CompletePlan,
701    /// Semantic matcher node that emits rows for downstream output operators.
702    RowStreamNode,
703    /// Semantic matcher node that finalizes one row per selected match.
704    OneRowNode,
705}
706
707/// Decoded identity for one retained selected-match summary output.
708#[derive(Clone, Debug, PartialEq, Eq)]
709pub struct DecodedSummaryAggregate {
710    /// Registered DataFusion aggregate function name.
711    pub function_name: String,
712    /// Aggregate arguments decoded against `[source_input, public_metadata, pattern_classifiers]`.
713    pub args: Vec<Expr>,
714    /// Whether the aggregate uses `DISTINCT`.
715    pub distinct: bool,
716    /// Optional aggregate `FILTER` predicate.
717    pub filter: Option<Expr>,
718    /// Aggregate `ORDER BY` expressions.
719    pub order_by: Vec<SortExpr>,
720    /// Optional aggregate null treatment.
721    pub null_treatment: Option<expr::NullTreatment>,
722}
723
724/// Validated source request decoded from one extension detail message.
725#[derive(Clone, Debug)]
726pub struct DecodedMatchRecognizeDetail {
727    /// Bound source request encoded by the payload.
728    pub spec: BoundMatchSpec,
729    /// Planning capabilities declared by the payload's required features.
730    pub capabilities: MatchRecognizePlanningCapabilities,
731    /// Whether the payload declares match-aware DEFINE requirements.
732    ///
733    /// This is wire metadata, not proof that executable admission has succeeded.
734    pub declares_match_aware_defines: bool,
735    /// Exact output schema declared at the extension boundary.
736    pub output_schema: NamedStruct,
737    /// Checked output contract of the decoded extension relation.
738    pub boundary: MatchRecognizeBoundary,
739    /// Ordinary-source passthrough outputs in payload order, resolved against
740    /// the consumed input. Required positional identity accompanies both
741    /// row-stream and selected-summary semantic boundaries.
742    pub retained_passthrough_input_fields: Vec<Column>,
743    /// Prepared window outputs identified by absolute output position and the
744    /// complete defining expression decoded against the consumed source input.
745    pub prepared_output_fields: Vec<(usize, Expr)>,
746    /// Selected-match summary outputs identified by absolute output position
747    /// and canonical aggregate identity decoded against the consumed source
748    /// input, public metadata, and pattern classifiers.
749    pub summary_output_fields: Vec<(usize, DecodedSummaryAggregate)>,
750}
751
752/// Decodes and validates one `MATCH_RECOGNIZE` Protobuf detail message against
753/// its input schema.
754///
755/// # Errors
756///
757/// Returns an error when the type URL is not [`MATCH_RECOGNIZE_TYPE_URL`], the
758/// Protobuf message is malformed, its schema version or required features are
759/// unsupported, an expression cannot be decoded against `input_schema`, or the
760/// resulting source specification is invalid.
761pub async fn decode_match_recognize_detail(
762    consumer: &impl SubstraitConsumer,
763    detail: &Any,
764    input_schema: &DFSchema,
765) -> Result<DecodedMatchRecognizeDetail> {
766    let (payload, capabilities, boundary) = decode_match_recognize_payload(detail)?;
767    decode_match_recognize_detail_from_payload(
768        consumer,
769        payload,
770        capabilities,
771        boundary,
772        input_schema,
773    )
774    .await
775}
776
777fn decode_match_recognize_payload(
778    detail: &Any,
779) -> Result<(
780    payload::MatchRecognizeRel,
781    MatchRecognizePlanningCapabilities,
782    MatchRecognizeBoundary,
783)> {
784    if detail.type_url != MATCH_RECOGNIZE_TYPE_URL {
785        return plan_err!(
786            "unknown MATCH_RECOGNIZE detail type URL: {}",
787            detail.type_url
788        );
789    }
790
791    let payload = wire::decode_detail(detail.value.as_ref())?;
792    validate_schema_version(payload.schema_version)?;
793    let capabilities = decode_capabilities(&payload.required_features)?;
794    let boundary = decode_boundary(&payload)?;
795    Ok((payload, capabilities, boundary))
796}
797
798/// Re-alias positional semantic-node input fields whose names or qualifiers lost
799/// SQL aliases across upstream Substrait relations.
800///
801/// Substrait `ProjectRel` strips column aliases and drops `SubqueryAlias` table
802/// qualifiers. A valid SQL query — such as chained `MATCH_RECOGNIZE` nodes where
803/// an inner semantic node exposes `__mr_*` outputs or a projection aliasing a
804/// `__mr_*` base column — can therefore arrive at an outer semantic node with
805/// reserved `__mr_*` field names or qualifiers. Because semantic-node inputs and
806/// outputs are strictly positional, introducing fresh unqualified names for only
807/// those offending columns preserves exact field ordinals, types, nullability,
808/// and metadata without weakening SQL validation.
809fn sanitize_semantic_node_input(input: LogicalPlan) -> Result<LogicalPlan> {
810    let needs_sanitizing = input
811        .schema()
812        .iter()
813        .any(|(qualifier, field)| field_needs_sanitizing(qualifier, field));
814    if !needs_sanitizing {
815        return Ok(input);
816    }
817
818    let mut used_names = input
819        .schema()
820        .fields()
821        .iter()
822        .map(|field| field.name().to_ascii_lowercase())
823        .collect::<BTreeSet<_>>();
824    let mut exprs = Vec::with_capacity(input.schema().fields().len());
825    for (index, (qualifier, field)) in input.schema().iter().enumerate() {
826        let column = Expr::Column(Column::new(qualifier.cloned(), field.name()));
827        if field_needs_sanitizing(qualifier, field) {
828            let mut candidate = format!("substrait_input_{index}");
829            let mut suffix = 0usize;
830            while !used_names.insert(candidate.to_ascii_lowercase()) {
831                candidate = format!("substrait_input_{index}_{suffix}");
832                suffix += 1;
833            }
834            exprs.push(column.alias(candidate));
835        } else {
836            exprs.push(column);
837        }
838    }
839
840    Ok(LogicalPlan::Projection(Projection::try_new(
841        exprs,
842        Arc::new(input),
843    )?))
844}
845
846fn field_needs_sanitizing(qualifier: Option<&TableReference>, field: &Field) -> bool {
847    is_reserved_internal_column_name(field.name())
848        || qualifier.is_some_and(has_reserved_relation)
849}
850
851fn has_reserved_relation(relation: &TableReference) -> bool {
852    [
853        relation.catalog(),
854        relation.schema(),
855        Some(relation.table()),
856    ]
857    .into_iter()
858    .flatten()
859    .any(is_reserved_internal_column_name)
860}
861
862async fn decode_match_recognize_detail_from_payload(
863    consumer: &impl SubstraitConsumer,
864    payload: payload::MatchRecognizeRel,
865    capabilities: MatchRecognizePlanningCapabilities,
866    boundary: MatchRecognizeBoundary,
867    input_schema: &DFSchema,
868) -> Result<DecodedMatchRecognizeDetail> {
869    if boundary != MatchRecognizeBoundary::CompletePlan
870        && !payload
871            .required_features
872            .iter()
873            .any(|feature| feature == DATAFUSION_WINDOW_MODIFIERS_FEATURE)
874    {
875        return plan_err!(
876            "semantic MATCH_RECOGNIZE Substrait payload missing required feature {}",
877            DATAFUSION_WINDOW_MODIFIERS_FEATURE
878        );
879    }
880    let declares_match_aware_defines = payload
881        .required_features
882        .iter()
883        .any(|feature| feature == MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE);
884    let mut seen = BTreeSet::new();
885    let retained_passthrough_input_fields = payload
886        .retained_passthrough_input_fields
887        .iter()
888        .map(|&index| {
889            if !seen.insert(index) {
890                return plan_err!(
891                    "MATCH_RECOGNIZE retained_passthrough_input_fields contains duplicate input_field {}",
892                    index
893                );
894            }
895            decode_input_field(input_schema, index)
896        })
897        .collect::<Result<Vec<_>>>()?;
898    let output_schema = payload.output_schema.ok_or_else(|| {
899        datafusion::common::DataFusionError::Plan(
900            "MATCH_RECOGNIZE Substrait payload missing output_schema".to_string(),
901        )
902    })?;
903    let output_count = output_schema
904        .r#struct
905        .as_ref()
906        .map_or(0, |schema| schema.types.len());
907    let retained_prefix_len = retained_passthrough_input_fields.len();
908    if retained_prefix_len > output_count {
909        return plan_err!(
910            "MATCH_RECOGNIZE retained_passthrough_input_fields exceeds the output field count"
911        );
912    }
913    let prepared_output_fields = decode_prepared_output_fields(
914        consumer,
915        input_schema,
916        output_count,
917        retained_prefix_len,
918        &payload.prepared_output_fields,
919    )
920    .await?;
921    let pattern = decode_pattern(payload.pattern)?;
922    if has_reluctant_quantifier(&pattern)
923        && !payload
924            .required_features
925            .iter()
926            .any(|feature| feature == MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE)
927    {
928        return plan_err!(
929            "MATCH_RECOGNIZE Substrait reluctant quantifier requires feature {}",
930            MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE
931        );
932    }
933
934    let pattern_symbols = payload
935        .symbols
936        .iter()
937        .map(|symbol| symbol.to_ascii_lowercase())
938        .collect::<BTreeSet<_>>();
939    let spec = MatchRecognizeSpec {
940        partition_by: decode_exprs(
941            consumer,
942            input_schema,
943            &pattern_symbols,
944            payload.partition_expressions,
945        )
946        .await?,
947        order_by: decode_source_sorts(
948            consumer,
949            input_schema,
950            &pattern_symbols,
951            payload.sorts,
952        )
953        .await?,
954        source_rows_per_match: decode_rows_per_match(payload.rows_per_match)?,
955        after_match_skip: decode_after_match_skip(payload.after_match_skip)?,
956        pattern,
957        symbols: payload.symbols,
958        definitions: decode_definitions(
959            consumer,
960            input_schema,
961            &pattern_symbols,
962            payload.definitions,
963        )
964        .await?,
965        measures: decode_measures(
966            consumer,
967            input_schema,
968            &pattern_symbols,
969            payload.measures,
970        )
971        .await?,
972        output: decode_output_contract(
973            consumer,
974            input_schema,
975            &pattern_symbols,
976            payload.output_contract,
977        )
978        .await?,
979    }
980    .try_new()
981    .map_err(|err| datafusion::common::DataFusionError::Plan(err.to_string()))?;
982    let expr_features = spec_expr_features(&spec)?;
983    if expr_features.has_logical_offset
984        && !payload
985            .required_features
986            .iter()
987            .any(|feature| feature == MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE)
988    {
989        return plan_err!(
990            "MATCH_RECOGNIZE Substrait logical navigation offset requires feature {}",
991            MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE
992        );
993    }
994    if expr_features.has_compound_navigation
995        && !payload
996            .required_features
997            .iter()
998            .any(|feature| feature == MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE)
999    {
1000        return plan_err!(
1001            "MATCH_RECOGNIZE Substrait compound navigation requires feature {}",
1002            MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE
1003        );
1004    }
1005    if expr_features.has_distinct_from
1006        && !payload
1007            .required_features
1008            .iter()
1009            .any(|feature| feature == MATCH_RECOGNIZE_DISTINCT_FROM_FEATURE)
1010    {
1011        return plan_err!(
1012            "MATCH_RECOGNIZE Substrait IS [NOT] DISTINCT FROM requires feature {}",
1013            MATCH_RECOGNIZE_DISTINCT_FROM_FEATURE
1014        );
1015    }
1016    let summary_output_fields = decode_summary_output_fields(
1017        consumer,
1018        input_schema,
1019        &spec.symbols,
1020        retained_prefix_len..output_count,
1021        &prepared_output_fields,
1022        &payload.summary_output_fields,
1023    )
1024    .await?;
1025
1026    Ok(DecodedMatchRecognizeDetail {
1027        spec,
1028        capabilities,
1029        declares_match_aware_defines,
1030        output_schema,
1031        boundary,
1032        retained_passthrough_input_fields,
1033        prepared_output_fields,
1034        summary_output_fields,
1035    })
1036}
1037
1038/// Check the wire declaration against the normalized DEFINE requirements before executable import.
1039fn validate_define_declaration(
1040    context: &mut impl MatchRecognizePlanningContext,
1041    input: &LogicalPlan,
1042    decoded: &DecodedMatchRecognizeDetail,
1043) -> Result<()> {
1044    let requirements = analyze_match_recognize_requirements(
1045        context,
1046        input,
1047        &decoded.spec,
1048        decoded.capabilities,
1049    )?;
1050    if requirements.requires_match_aware_defines()
1051        && !decoded.declares_match_aware_defines
1052    {
1053        return plan_err!(
1054            "MATCH_RECOGNIZE Substrait payload with match-aware DEFINEs is missing required feature {}",
1055            MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE
1056        );
1057    }
1058    Ok(())
1059}
1060
1061async fn decode_prepared_output_fields(
1062    consumer: &impl SubstraitConsumer,
1063    input_schema: &DFSchema,
1064    output_count: usize,
1065    retained_prefix_len: usize,
1066    fields: &[payload::PreparedOutputField],
1067) -> Result<Vec<(usize, Expr)>> {
1068    let mut seen = BTreeSet::new();
1069    let mut decoded = Vec::with_capacity(fields.len());
1070    for field in fields {
1071        let index = usize::try_from(field.output_field).map_err(|_| {
1072            datafusion::common::DataFusionError::Plan(
1073                "MATCH_RECOGNIZE prepared output_field exceeds the addressable output"
1074                    .into(),
1075            )
1076        })?;
1077        if index >= output_count {
1078            return plan_err!(
1079                "MATCH_RECOGNIZE prepared output_field {} is out of bounds for {} output fields",
1080                index,
1081                output_count
1082            );
1083        }
1084        if index < retained_prefix_len {
1085            return plan_err!(
1086                "MATCH_RECOGNIZE prepared output_field {} overlaps the ordinary-source output prefix",
1087                index
1088            );
1089        }
1090        if !seen.insert(index) {
1091            return plan_err!(
1092                "MATCH_RECOGNIZE prepared_output_fields contains duplicate output_field {}",
1093                index
1094            );
1095        }
1096        let expression = field.expression.as_ref().ok_or_else(|| {
1097            datafusion::common::DataFusionError::Plan(
1098                "MATCH_RECOGNIZE prepared output_field is missing expression".into(),
1099            )
1100        })?;
1101        let expression = consumer
1102            .consume_expression(expression, input_schema)
1103            .await?;
1104        if !matches!(expression, Expr::WindowFunction(_)) {
1105            return plan_err!(
1106                "MATCH_RECOGNIZE prepared output_field expression must be a window expression"
1107            );
1108        }
1109        decoded.push((index, expression));
1110    }
1111    Ok(decoded)
1112}
1113
1114async fn decode_summary_output_fields(
1115    consumer: &impl SubstraitConsumer,
1116    input_schema: &DFSchema,
1117    symbols: &[String],
1118    valid_outputs: Range<usize>,
1119    prepared_output_fields: &[(usize, Expr)],
1120    fields: &[payload::SummaryOutputField],
1121) -> Result<Vec<(usize, DecodedSummaryAggregate)>> {
1122    if fields.is_empty() {
1123        return Ok(Vec::new());
1124    }
1125    let summary_schema = summary_wire_decode_schema(input_schema, symbols)?;
1126    let prepared_positions = prepared_output_fields
1127        .iter()
1128        .map(|(index, _)| *index)
1129        .collect::<BTreeSet<_>>();
1130    let mut seen = BTreeSet::new();
1131    let mut decoded = Vec::with_capacity(fields.len());
1132    for field in fields {
1133        let index = usize::try_from(field.output_field).map_err(|_| {
1134            datafusion::common::DataFusionError::Plan(
1135                "MATCH_RECOGNIZE summary output_field exceeds the addressable output"
1136                    .into(),
1137            )
1138        })?;
1139        if index >= valid_outputs.end {
1140            return plan_err!(
1141                "MATCH_RECOGNIZE summary output_field {} is out of bounds for {} output fields",
1142                index,
1143                valid_outputs.end
1144            );
1145        }
1146        if index < valid_outputs.start {
1147            return plan_err!(
1148                "MATCH_RECOGNIZE summary output_field {} overlaps the ordinary-source output prefix",
1149                index
1150            );
1151        }
1152        if prepared_positions.contains(&index) {
1153            return plan_err!(
1154                "MATCH_RECOGNIZE summary output_field {} overlaps prepared_output_fields",
1155                index
1156            );
1157        }
1158        if !seen.insert(index) {
1159            return plan_err!(
1160                "MATCH_RECOGNIZE summary_output_fields contains duplicate output_field {}",
1161                index
1162            );
1163        }
1164        if field.function_name.trim().is_empty() {
1165            return plan_err!(
1166                "MATCH_RECOGNIZE summary output_field {} is missing function_name",
1167                index
1168            );
1169        }
1170        let mut args = Vec::with_capacity(field.args.len());
1171        for arg in &field.args {
1172            args.push(consumer.consume_expression(arg, &summary_schema).await?);
1173        }
1174        let filter = match &field.filter {
1175            Some(filter) => {
1176                Some(consumer.consume_expression(filter, &summary_schema).await?)
1177            }
1178            None => None,
1179        };
1180        let mut order_by = Vec::with_capacity(field.order_by.len());
1181        for sort in &field.order_by {
1182            let expr = sort.expr.as_ref().ok_or_else(|| {
1183                datafusion::common::DataFusionError::Plan(
1184                    "MATCH_RECOGNIZE summary ORDER BY sort expression missing expr"
1185                        .into(),
1186                )
1187            })?;
1188            let expr = consumer.consume_expression(expr, &summary_schema).await?;
1189            let asc = matches!(
1190                decode_sort_direction(sort.direction, "summary ORDER BY")?,
1191                MatchRecognizeSortDirection::Asc
1192            );
1193            let nulls_first = matches!(
1194                decode_null_ordering(sort.null_ordering, "summary ORDER BY")?,
1195                MatchRecognizeNullOrdering::First
1196            );
1197            order_by.push(SortExpr::new(expr, asc, nulls_first));
1198        }
1199        let null_treatment = decode_null_treatment(field.null_treatment)?;
1200        decoded.push((
1201            index,
1202            DecodedSummaryAggregate {
1203                function_name: field.function_name.clone(),
1204                args,
1205                distinct: field.distinct,
1206                filter,
1207                order_by,
1208                null_treatment,
1209            },
1210        ));
1211    }
1212    Ok(decoded)
1213}
1214
1215fn summary_wire_decode_schema(
1216    input_schema: &DFSchema,
1217    symbols: &[String],
1218) -> Result<DFSchemaRef> {
1219    let input_schema_ref = Arc::new(input_schema.clone());
1220    MatchRecognizeOutputSpec::full_from(&input_schema_ref, symbols)
1221        .build_df_schema(input_schema)
1222}
1223
1224fn normalize_decoded_summary(
1225    summary: &DecodedSummaryAggregate,
1226    summary_schema: &DFSchema,
1227) -> Result<DecodedSummaryAggregate> {
1228    let normalize = |expr: &Expr| normalize_wire_expr(expr.clone(), summary_schema);
1229    Ok(DecodedSummaryAggregate {
1230        function_name: summary.function_name.clone(),
1231        args: summary
1232            .args
1233            .iter()
1234            .map(normalize)
1235            .collect::<Result<Vec<_>>>()?,
1236        distinct: summary.distinct,
1237        filter: summary.filter.as_ref().map(normalize).transpose()?,
1238        order_by: summary
1239            .order_by
1240            .iter()
1241            .map(|sort| {
1242                Ok(SortExpr::new(
1243                    normalize(&sort.expr)?,
1244                    sort.asc,
1245                    sort.nulls_first,
1246                ))
1247            })
1248            .collect::<Result<Vec<_>>>()?,
1249        null_treatment: summary.null_treatment,
1250    })
1251}
1252
1253fn planned_summary_identity(
1254    summary: &LogicalSelectedMatchSummary,
1255    node: &MatchRecognize,
1256    source_schema: &DFSchema,
1257    summary_schema: &DFSchema,
1258) -> Result<DecodedSummaryAggregate> {
1259    let normalize = |expr: &Expr| -> Result<Expr> {
1260        let expanded =
1261            producer::expand_prepared_source_exprs(expr.clone(), node, source_schema)?;
1262        normalize_wire_expr(expanded, summary_schema)
1263    };
1264    let aggregate = summary.aggregate();
1265    let params = &aggregate.params;
1266    Ok(DecodedSummaryAggregate {
1267        function_name: aggregate.func.name().to_string(),
1268        args: params
1269            .args
1270            .iter()
1271            .map(normalize)
1272            .collect::<Result<Vec<_>>>()?,
1273        distinct: params.distinct,
1274        filter: params.filter.as_deref().map(normalize).transpose()?,
1275        order_by: params
1276            .order_by
1277            .iter()
1278            .map(|sort| {
1279                Ok(SortExpr::new(
1280                    normalize(&sort.expr)?,
1281                    sort.asc,
1282                    sort.nulls_first,
1283                ))
1284            })
1285            .collect::<Result<Vec<_>>>()?,
1286        null_treatment: params.null_treatment,
1287    })
1288}
1289
1290fn typed_null_identity(data_type: &DataType) -> Result<Expr> {
1291    let wire_type = schema::bare_decoded_type(data_type);
1292    match ScalarValue::try_from(&wire_type)? {
1293        ScalarValue::Date64(value) => Ok(Expr::Cast(expr::Cast::new(
1294            Box::new(Expr::Literal(ScalarValue::Int64(value), None)),
1295            DataType::Date64,
1296        ))),
1297        value => Ok(Expr::Literal(value, None)),
1298    }
1299}
1300
1301fn normalize_wire_scalar(value: &ScalarValue) -> Result<Option<ScalarValue>> {
1302    use datafusion::arrow::array::{Array, AsArray, MapArray, new_empty_array};
1303    use datafusion::arrow::buffer::OffsetBuffer;
1304    use datafusion::common::scalar::ScalarStructBuilder;
1305
1306    match value {
1307        v if v.is_null() && !v.data_type().is_null() => {
1308            let dt = v.data_type();
1309            let bare = schema::bare_decoded_type(&dt);
1310            if bare != dt {
1311                Ok(Some(ScalarValue::try_from(&bare)?))
1312            } else {
1313                Ok(None)
1314            }
1315        }
1316        ScalarValue::TimestampSecond(v, Some(tz)) if tz.as_ref() != "UTC" => {
1317            Ok(Some(ScalarValue::TimestampSecond(*v, Some("UTC".into()))))
1318        }
1319        ScalarValue::TimestampMillisecond(v, Some(tz)) if tz.as_ref() != "UTC" => Ok(
1320            Some(ScalarValue::TimestampMillisecond(*v, Some("UTC".into()))),
1321        ),
1322        ScalarValue::TimestampMicrosecond(v, Some(tz)) if tz.as_ref() != "UTC" => Ok(
1323            Some(ScalarValue::TimestampMicrosecond(*v, Some("UTC".into()))),
1324        ),
1325        ScalarValue::TimestampNanosecond(v, Some(tz)) if tz.as_ref() != "UTC" => Ok(
1326            Some(ScalarValue::TimestampNanosecond(*v, Some("UTC".into()))),
1327        ),
1328        ScalarValue::Struct(s) => {
1329            let mut builder = ScalarStructBuilder::new();
1330            for (index, col) in s.columns().iter().enumerate() {
1331                let child = ScalarValue::try_from_array(col.as_ref(), 0)?;
1332                let child = normalize_wire_scalar(&child)?.unwrap_or(child);
1333                builder = builder.with_scalar(
1334                    Field::new(format!("c{index}"), child.data_type(), true),
1335                    child,
1336                );
1337            }
1338            let normalized = builder.build()?;
1339            Ok((normalized != *value).then_some(normalized))
1340        }
1341        ScalarValue::List(l) => {
1342            let DataType::List(item_field) = l.data_type() else {
1343                return Ok(None);
1344            };
1345            let values = l.value(0);
1346            let normalized = if values.is_empty() {
1347                let elem_type = schema::bare_decoded_type(item_field.data_type());
1348                ScalarValue::List(ScalarValue::new_list_nullable(&[], &elem_type))
1349            } else {
1350                let mut elements = Vec::with_capacity(values.len());
1351                for i in 0..values.len() {
1352                    let elem = ScalarValue::try_from_array(values.as_ref(), i)?;
1353                    elements.push(normalize_wire_scalar(&elem)?.unwrap_or(elem));
1354                }
1355                let elem_type = elements[0].data_type();
1356                ScalarValue::List(ScalarValue::new_list_nullable(&elements, &elem_type))
1357            };
1358            Ok((normalized != *value).then_some(normalized))
1359        }
1360        ScalarValue::LargeList(l) => {
1361            let DataType::LargeList(item_field) = l.data_type() else {
1362                return Ok(None);
1363            };
1364            let values = l.value(0);
1365            let normalized = if values.is_empty() {
1366                let elem_type = schema::bare_decoded_type(item_field.data_type());
1367                ScalarValue::LargeList(ScalarValue::new_large_list(&[], &elem_type))
1368            } else {
1369                let mut elements = Vec::with_capacity(values.len());
1370                for i in 0..values.len() {
1371                    let elem = ScalarValue::try_from_array(values.as_ref(), i)?;
1372                    elements.push(normalize_wire_scalar(&elem)?.unwrap_or(elem));
1373                }
1374                let elem_type = elements[0].data_type();
1375                ScalarValue::LargeList(ScalarValue::new_large_list(&elements, &elem_type))
1376            };
1377            Ok((normalized != *value).then_some(normalized))
1378        }
1379        ScalarValue::Map(m) => {
1380            let DataType::Map(entries_field, _) = m.data_type() else {
1381                return Ok(None);
1382            };
1383            let DataType::Struct(kv_fields) = entries_field.data_type() else {
1384                return Ok(None);
1385            };
1386            if kv_fields.len() != 2 {
1387                return Ok(None);
1388            }
1389            let entries = m.value(0);
1390            let normalized = if entries.is_empty() {
1391                let key_field = Field::new(
1392                    "key",
1393                    schema::bare_decoded_type(kv_fields[0].data_type()),
1394                    false,
1395                );
1396                let value_field = Field::new(
1397                    "value",
1398                    schema::bare_decoded_type(kv_fields[1].data_type()),
1399                    kv_fields[1].is_nullable(),
1400                );
1401                let entries_type =
1402                    Field::new_struct("entries", vec![key_field, value_field], false);
1403                let struct_array = new_empty_array(entries_type.data_type())
1404                    .as_struct()
1405                    .to_owned();
1406                ScalarValue::Map(Arc::new(MapArray::new(
1407                    Arc::new(entries_type),
1408                    OffsetBuffer::new(vec![0, 0].into()),
1409                    struct_array,
1410                    None,
1411                    false,
1412                )))
1413            } else {
1414                let mut rows = Vec::with_capacity(entries.len());
1415                for i in 0..entries.len() {
1416                    let key_sv =
1417                        ScalarValue::try_from_array(entries.column(0).as_ref(), i)?;
1418                    let key_sv = normalize_wire_scalar(&key_sv)?.unwrap_or(key_sv);
1419                    let val_sv =
1420                        ScalarValue::try_from_array(entries.column(1).as_ref(), i)?;
1421                    let val_sv = normalize_wire_scalar(&val_sv)?.unwrap_or(val_sv);
1422                    rows.push(
1423                        ScalarStructBuilder::new()
1424                            .with_scalar(
1425                                Field::new("key", key_sv.data_type(), false),
1426                                key_sv,
1427                            )
1428                            .with_scalar(
1429                                Field::new("value", val_sv.data_type(), true),
1430                                val_sv,
1431                            )
1432                            .build()?,
1433                    );
1434                }
1435                ScalarValue::Map(Arc::new(MapArray::new(
1436                    Arc::new(Field::new("entries", rows[0].data_type(), false)),
1437                    OffsetBuffer::new(vec![0, rows.len() as i32].into()),
1438                    ScalarValue::iter_to_array(rows)?.as_struct().to_owned(),
1439                    None,
1440                    false,
1441                )))
1442            };
1443            Ok((normalized != *value).then_some(normalized))
1444        }
1445        _ => Ok(None),
1446    }
1447}
1448
1449fn normalize_wire_literal(value: &ScalarValue) -> Result<Option<Expr>> {
1450    match value {
1451        ScalarValue::Date64(v) => Ok(Some(Expr::Cast(expr::Cast::new(
1452            Box::new(Expr::Literal(ScalarValue::Int64(*v), None)),
1453            DataType::Date64,
1454        )))),
1455        other => Ok(normalize_wire_scalar(other)?.map(|v| Expr::Literal(v, None))),
1456    }
1457}
1458
1459fn is_date64_millis_cast(expr: &Expr) -> bool {
1460    matches!(
1461        expr,
1462        Expr::Cast(cast)
1463            if matches!(cast.expr.as_ref(), Expr::Literal(ScalarValue::Int64(_), _))
1464                && cast.field.as_ref() == &Field::new("", DataType::Date64, true)
1465    )
1466}
1467
1468fn is_wire_rewritten_inert_when(expr: &Expr) -> bool {
1469    matches!(expr, Expr::Literal(value, _) if value.is_null())
1470        || is_date64_millis_cast(expr)
1471}
1472
1473fn strip_wire_ambiguous_null_base_guard(
1474    mut case: expr::Case,
1475    schema: &DFSchema,
1476) -> Result<(expr::Case, bool)> {
1477    if case.expr.is_some() || case.when_then_expr.len() < 2 {
1478        return Ok((case, false));
1479    }
1480    let (Expr::IsNull(base), guard_then) = (
1481        case.when_then_expr[0].0.as_ref(),
1482        case.when_then_expr[0].1.as_ref(),
1483    ) else {
1484        return Ok((case, false));
1485    };
1486    if base.is_volatile() || !base.nullable(schema)? {
1487        return Ok((case, false));
1488    }
1489    let expected_guard_then = match &case.else_expr {
1490        Some(else_expr) => else_expr.as_ref().clone(),
1491        None => {
1492            let result_type = case.when_then_expr[1].1.get_type(schema)?;
1493            typed_null_identity(&result_type)?
1494        }
1495    };
1496    if guard_then != &expected_guard_then {
1497        return Ok((case, false));
1498    }
1499    let mut has_wire_rewritten = false;
1500    for (when, _) in &case.when_then_expr[1..] {
1501        let Expr::BinaryExpr(binary) = when.as_ref() else {
1502            return Ok((case, false));
1503        };
1504        if binary.op != Operator::Eq || binary.left.as_ref() != base.as_ref() {
1505            return Ok((case, false));
1506        }
1507        let right = binary.right.as_ref();
1508        if is_wire_rewritten_inert_when(right) {
1509            has_wire_rewritten = true;
1510        } else if !matches!(right, Expr::Literal(..) | Expr::Column(_)) {
1511            return Ok((case, false));
1512        }
1513    }
1514    if !has_wire_rewritten {
1515        return Ok((case, false));
1516    }
1517    case.when_then_expr.remove(0);
1518    Ok((case, true))
1519}
1520
1521pub(crate) fn normalize_wire_expr(expression: Expr, schema: &DFSchema) -> Result<Expr> {
1522    // Desugar simple CASE top-down before child literal/cast/alias rewrites so
1523    // `when_operand_is_inert` and `base.nullable` inspect the same unrewritten
1524    // operands that DataFusion's Substrait `from_case` sees on export.
1525    let expression = expression
1526        .transform_down(|expr| {
1527            let Expr::Case(case) = expr else {
1528                return Ok(Transformed::no(expr));
1529            };
1530            if !case.expr.as_deref().is_some_and(|base| !base.is_volatile()) {
1531                return Ok(Transformed::no(Expr::Case(case)));
1532            }
1533            let base = case.expr.expect("checked Some above");
1534            let when_operand_is_inert = |(when, _): &(Box<Expr>, Box<Expr>)| {
1535                matches!(when.as_ref(), Expr::Literal(..) | Expr::Column(_))
1536            };
1537            let null_base_guard = !case.when_then_expr.iter().all(when_operand_is_inert)
1538                && base.nullable(schema)?;
1539            let mut when_then_expr = Vec::with_capacity(
1540                case.when_then_expr.len() + usize::from(null_base_guard),
1541            );
1542            if null_base_guard {
1543                let then = match &case.else_expr {
1544                    Some(else_expr) => else_expr.as_ref().clone(),
1545                    None => match case.when_then_expr.first() {
1546                        Some((_, then)) => {
1547                            let result_type = then.get_type(schema)?;
1548                            typed_null_identity(&result_type)?
1549                        }
1550                        None => {
1551                            return Ok(Transformed::no(Expr::Case(expr::Case {
1552                                expr: Some(base),
1553                                when_then_expr: case.when_then_expr,
1554                                else_expr: case.else_expr,
1555                            })));
1556                        }
1557                    },
1558                };
1559                when_then_expr
1560                    .push((Box::new(base.as_ref().clone().is_null()), Box::new(then)));
1561            }
1562            for (when, then) in case.when_then_expr {
1563                when_then_expr
1564                    .push((Box::new(Expr::eq(base.as_ref().clone(), *when)), then));
1565            }
1566            Ok(Transformed::yes(Expr::Case(expr::Case {
1567                expr: None,
1568                when_then_expr,
1569                else_expr: case.else_expr,
1570            })))
1571        })?
1572        .data;
1573    Ok(expression
1574        .transform_up(|expr| {
1575            let mut changed = false;
1576            let expr = match expr {
1577                Expr::Alias(alias) => {
1578                    changed = true;
1579                    *alias.expr
1580                }
1581                Expr::Literal(value, Some(_)) => {
1582                    changed = true;
1583                    Expr::Literal(value, None)
1584                }
1585                other => other,
1586            };
1587            match expr {
1588                Expr::WindowFunction(mut window) => {
1589                    // Substrait represents unbounded endpoints without a type.
1590                    // Their original NULL type does not affect frame identity.
1591                    for bound in [
1592                        &mut window.params.window_frame.start_bound,
1593                        &mut window.params.window_frame.end_bound,
1594                    ] {
1595                        if let WindowFrameBound::Preceding(value)
1596                        | WindowFrameBound::Following(value) = bound
1597                            && value.is_null()
1598                            && *value != ScalarValue::Null
1599                        {
1600                            *value = ScalarValue::Null;
1601                            changed = true;
1602                        }
1603                    }
1604                    Ok(if changed {
1605                        Transformed::yes(Expr::WindowFunction(window))
1606                    } else {
1607                        Transformed::no(Expr::WindowFunction(window))
1608                    })
1609                }
1610                Expr::Column(column) => {
1611                    let resolved = if let Ok(index) = schema.index_of_column(&column) {
1612                        let (qualifier, field) = schema.qualified_field(index);
1613                        Column::new(qualifier.cloned(), field.name())
1614                    } else {
1615                        column.clone()
1616                    };
1617                    Ok(if resolved != column {
1618                        Transformed::yes(Expr::Column(resolved))
1619                    } else if changed {
1620                        Transformed::yes(Expr::Column(column))
1621                    } else {
1622                        Transformed::no(Expr::Column(column))
1623                    })
1624                }
1625                Expr::Cast(cast)
1626                    if matches!(
1627                        cast.expr.as_ref(),
1628                        Expr::Literal(ScalarValue::Null, _)
1629                    ) && cast.field.as_ref()
1630                        == &Field::new("", cast.field.data_type().clone(), true) =>
1631                {
1632                    Ok(Transformed::yes(typed_null_identity(
1633                        cast.field.data_type(),
1634                    )?))
1635                }
1636                Expr::Cast(mut cast)
1637                    if cast.field.as_ref()
1638                        == &Field::new("", cast.field.data_type().clone(), true) =>
1639                {
1640                    let bare = schema::bare_decoded_type(cast.field.data_type());
1641                    if bare != *cast.field.data_type() {
1642                        cast.field = Arc::new(Field::new("", bare, true));
1643                        Ok(Transformed::yes(Expr::Cast(cast)))
1644                    } else if changed {
1645                        Ok(Transformed::yes(Expr::Cast(cast)))
1646                    } else {
1647                        Ok(Transformed::no(Expr::Cast(cast)))
1648                    }
1649                }
1650                Expr::TryCast(mut try_cast)
1651                    if try_cast.field.as_ref()
1652                        == &Field::new("", try_cast.field.data_type().clone(), true) =>
1653                {
1654                    let bare = schema::bare_decoded_type(try_cast.field.data_type());
1655                    if bare != *try_cast.field.data_type() {
1656                        try_cast.field = Arc::new(Field::new("", bare, true));
1657                        Ok(Transformed::yes(Expr::TryCast(try_cast)))
1658                    } else if changed {
1659                        Ok(Transformed::yes(Expr::TryCast(try_cast)))
1660                    } else {
1661                        Ok(Transformed::no(Expr::TryCast(try_cast)))
1662                    }
1663                }
1664                Expr::Literal(value, meta) => {
1665                    if let Some(normalized) = normalize_wire_literal(&value)? {
1666                        Ok(Transformed::yes(normalized))
1667                    } else if changed {
1668                        Ok(Transformed::yes(Expr::Literal(value, meta)))
1669                    } else {
1670                        Ok(Transformed::no(Expr::Literal(value, meta)))
1671                    }
1672                }
1673                Expr::Between(between) => {
1674                    let expr = *between.expr;
1675                    let desugared = if between.negated {
1676                        Expr::or(
1677                            Expr::lt(expr.clone(), *between.low),
1678                            Expr::lt(*between.high, expr),
1679                        )
1680                    } else {
1681                        Expr::and(
1682                            Expr::lt_eq(*between.low, expr.clone()),
1683                            Expr::lt_eq(expr, *between.high),
1684                        )
1685                    };
1686                    Ok(Transformed::yes(desugared))
1687                }
1688                Expr::InList(mut in_list) if in_list.negated => {
1689                    in_list.negated = false;
1690                    Ok(Transformed::yes(Expr::Not(Box::new(Expr::InList(in_list)))))
1691                }
1692                Expr::Like(mut like) if like.negated => {
1693                    like.negated = false;
1694                    Ok(Transformed::yes(Expr::Not(Box::new(Expr::Like(like)))))
1695                }
1696                Expr::Case(case) if case.expr.is_none() => {
1697                    // Canonicalize a leading NULL-base guard when every WHEN
1698                    // operand is inert after wire normalization and at least one
1699                    // is a wire-rewritten typed NULL or Date64 millisecond cast.
1700                    // Separate encoding of structured expressions vs wire output
1701                    // fields can flip `when_operand_is_inert` on those two literal forms.
1702                    let (case, stripped) =
1703                        strip_wire_ambiguous_null_base_guard(case, schema)?;
1704                    Ok(if stripped || changed {
1705                        Transformed::yes(Expr::Case(case))
1706                    } else {
1707                        Transformed::no(Expr::Case(case))
1708                    })
1709                }
1710                other => Ok(if changed {
1711                    Transformed::yes(other)
1712                } else {
1713                    Transformed::no(other)
1714                }),
1715            }
1716        })?
1717        .data)
1718}
1719
1720fn folded_required_count_identity(
1721    identity: &DecodedSummaryAggregate,
1722    source_input: &LogicalPlan,
1723    symbols: &[String],
1724) -> Option<DecodedSummaryAggregate> {
1725    if identity.function_name != count_udaf().name()
1726        || identity.distinct
1727        || identity.null_treatment.is_some()
1728        || !identity.order_by.is_empty()
1729    {
1730        return None;
1731    }
1732    let [Expr::Column(column)] = identity.args.as_slice() else {
1733        return None;
1734    };
1735    let source_schema = source_input.schema();
1736    let index = source_schema.maybe_index_of_column(column)?;
1737    let field = source_schema.field(index);
1738    if is_reserved_internal_column_name(field.name())
1739        || field.is_nullable()
1740        || can_have_nulls_outside_bitmap(field.data_type())
1741        || !is_stored_source_column(source_input, index)
1742    {
1743        return None;
1744    }
1745    let filter = identity.filter.as_ref()?;
1746    if !is_assigned_classifier_filter(filter, symbols) {
1747        return None;
1748    }
1749    Some(DecodedSummaryAggregate {
1750        function_name: identity.function_name.clone(),
1751        args: vec![Expr::Literal(ScalarValue::Int64(Some(1)), None)],
1752        distinct: false,
1753        filter: Some(filter.clone()),
1754        order_by: Vec::new(),
1755        null_treatment: None,
1756    })
1757}
1758
1759fn is_assigned_classifier_filter(filter: &Expr, symbols: &[String]) -> bool {
1760    match filter {
1761        Expr::IsNotNull(inner) => matches!(
1762            inner.as_ref(),
1763            Expr::Column(column)
1764                if column.relation.is_none()
1765                    && column.name == MatchMetadataColumn::Classifier.as_ref()
1766        ),
1767        Expr::Column(column) => {
1768            column.relation.is_none()
1769                && symbols
1770                    .iter()
1771                    .any(|symbol| classifier_bits_col_name(symbol) == column.name)
1772        }
1773        _ => false,
1774    }
1775}
1776
1777fn is_stored_source_column(mut input: &LogicalPlan, mut col_index: usize) -> bool {
1778    loop {
1779        match input {
1780            LogicalPlan::SubqueryAlias(alias) => input = &alias.input,
1781            LogicalPlan::Filter(filter) => input = &filter.input,
1782            LogicalPlan::Projection(projection) => {
1783                let Some(mut expr) = projection.expr.get(col_index) else {
1784                    return false;
1785                };
1786                while let Expr::Alias(alias) = expr {
1787                    expr = alias.expr.as_ref();
1788                }
1789                let Expr::Column(column) = expr else {
1790                    return false;
1791                };
1792                let Some(next_index) =
1793                    projection.input.schema().maybe_index_of_column(column)
1794                else {
1795                    return false;
1796                };
1797                input = &projection.input;
1798                col_index = next_index;
1799            }
1800            LogicalPlan::TableScan(scan) => {
1801                return scan.source.table_type() == TableType::Base
1802                    && scan.source.get_logical_plan().is_none();
1803            }
1804            _ => return false,
1805        }
1806    }
1807}
1808
1809fn decode_boundary(
1810    payload: &payload::MatchRecognizeRel,
1811) -> Result<MatchRecognizeBoundary> {
1812    if !payload.retained_passthrough_input_fields.is_empty() && !payload.semantic_node {
1813        return plan_err!(
1814            "MATCH_RECOGNIZE retained_passthrough_input_fields requires positional semantic-node output"
1815        );
1816    }
1817    if !payload.prepared_output_fields.is_empty() && !payload.semantic_node {
1818        return plan_err!(
1819            "MATCH_RECOGNIZE prepared_output_fields requires positional semantic-node output"
1820        );
1821    }
1822    if !payload.summary_output_fields.is_empty()
1823        && (!payload.semantic_node || !payload.semantic_node_finalizes_one_row)
1824    {
1825        return plan_err!(
1826            "MATCH_RECOGNIZE summary_output_fields requires one-row semantic-node output"
1827        );
1828    }
1829    let finalizes_one_row = payload
1830        .required_features
1831        .iter()
1832        .any(|feature| feature == DATAFUSION_SEMANTIC_ONE_ROW_FEATURE);
1833    if payload.semantic_node_finalizes_one_row != finalizes_one_row {
1834        return plan_err!(
1835            "MATCH_RECOGNIZE Substrait semantic_node_finalizes_one_row must agree with required feature {}",
1836            DATAFUSION_SEMANTIC_ONE_ROW_FEATURE
1837        );
1838    }
1839    match (
1840        payload.semantic_node,
1841        payload.semantic_node_finalizes_one_row,
1842    ) {
1843        (false, false) => Ok(MatchRecognizeBoundary::CompletePlan),
1844        (true, false) => Ok(MatchRecognizeBoundary::RowStreamNode),
1845        (true, true) => Ok(MatchRecognizeBoundary::OneRowNode),
1846        (false, true) => plan_err!(
1847            "MATCH_RECOGNIZE Substrait native ONE ROW finalization requires semantic_node=true"
1848        ),
1849    }
1850}
1851
1852pub(super) fn validate_schema_version(schema_version: Option<u32>) -> Result<()> {
1853    let Some(schema_version) = schema_version else {
1854        return plan_err!("MATCH_RECOGNIZE Substrait payload missing schema_version");
1855    };
1856    if schema_version == MATCH_RECOGNIZE_SCHEMA_VERSION {
1857        return Ok(());
1858    }
1859    plan_err!(
1860        "unsupported MATCH_RECOGNIZE Substrait payload schema_version {}; expected {}",
1861        schema_version,
1862        MATCH_RECOGNIZE_SCHEMA_VERSION
1863    )
1864}
1865
1866pub(super) fn decode_capabilities(
1867    features: &[String],
1868) -> Result<MatchRecognizePlanningCapabilities> {
1869    let features = features.iter().map(String::as_str).collect::<BTreeSet<_>>();
1870    if !features.contains(MATCH_RECOGNIZE_EXTENSION_FEATURE) {
1871        return plan_err!(
1872            "MATCH_RECOGNIZE Substrait payload missing required feature {}",
1873            MATCH_RECOGNIZE_EXTENSION_FEATURE
1874        );
1875    }
1876
1877    if !features.contains(MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE) {
1878        return plan_err!(
1879            "MATCH_RECOGNIZE Substrait payload missing required feature {}",
1880            MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE
1881        );
1882    }
1883
1884    for &feature in &features {
1885        match feature {
1886            MATCH_RECOGNIZE_EXTENSION_FEATURE
1887            | MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE
1888            | MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE
1889            | MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE
1890            | MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE
1891            | MATCH_RECOGNIZE_DISTINCT_FROM_FEATURE
1892            | MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE
1893            | DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE
1894            | DATAFUSION_EXCLUDED_FEATURE
1895            | DATAFUSION_WINDOW_MODIFIERS_FEATURE
1896            | DATAFUSION_SEMANTIC_ONE_ROW_FEATURE => {}
1897            _ => {
1898                return plan_err!(
1899                    "unknown MATCH_RECOGNIZE Substrait required feature {}",
1900                    feature
1901                );
1902            }
1903        }
1904    }
1905
1906    Ok(MatchRecognizePlanningCapabilities::restricted(
1907        features.contains(DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE),
1908        features.contains(DATAFUSION_EXCLUDED_FEATURE),
1909    ))
1910}
1911
1912pub(super) fn decode_input_field(input_schema: &DFSchema, index: u32) -> Result<Column> {
1913    let index = usize::try_from(index).map_err(|_| {
1914        datafusion::common::DataFusionError::Plan(
1915            "MATCH_RECOGNIZE Substrait input_field exceeds the addressable input".into(),
1916        )
1917    })?;
1918    if index >= input_schema.fields().len() {
1919        return plan_err!(
1920            "MATCH_RECOGNIZE Substrait input_field {} is out of bounds for {} input fields",
1921            index,
1922            input_schema.fields().len()
1923        );
1924    }
1925    let (qualifier, field) = input_schema.qualified_field(index);
1926    let column = Column::new(qualifier.cloned(), field.name());
1927    let identities = input_schema
1928        .iter()
1929        .filter(|(candidate_qualifier, candidate)| {
1930            *candidate_qualifier == qualifier && candidate.name() == field.name()
1931        })
1932        .count();
1933    if identities != 1 || input_schema.index_of_column(&column)? != index {
1934        return plan_err!(
1935            "MATCH_RECOGNIZE Substrait input_field {} does not identify an unambiguous input column",
1936            index
1937        );
1938    }
1939    Ok(column)
1940}