Skip to main content

datafusion_match_recognize/planning/source/
validate.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 std::collections::BTreeSet;
17
18use crate::core::{Pattern, is_reserved_internal_column_name};
19use datafusion::arrow::datatypes::{DataType, Field};
20use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
21use datafusion::common::{Column, DFSchema, Result, TableReference, plan_err};
22use datafusion::logical_expr::Expr;
23
24use super::bind::CanonicalSymbolMap;
25use super::expr::{BoundMatchExpr, MatchNavigation};
26use super::spec::BoundMatchSpec;
27
28#[derive(Clone, Copy)]
29pub(super) enum SourceClause {
30    PartitionBy,
31    OrderBy,
32    Define,
33    Measures,
34    ExplicitOutput,
35}
36
37impl SourceClause {
38    fn name(self) -> &'static str {
39        match self {
40            Self::PartitionBy => "PARTITION BY",
41            Self::OrderBy => "ORDER BY",
42            Self::Define => "DEFINE",
43            Self::Measures => "MEASURES",
44            Self::ExplicitOutput => "explicit output",
45        }
46    }
47
48    fn allows_row_pattern_constructs(self) -> bool {
49        matches!(self, Self::Define | Self::Measures | Self::ExplicitOutput)
50    }
51
52    fn allows_input_expr_windows(self) -> bool {
53        matches!(self, Self::Define)
54    }
55}
56pub(super) fn validate_clause_source_expr(
57    clause: SourceClause,
58    expr: &BoundMatchExpr,
59) -> Result<()> {
60    let mut pending = vec![(expr, false, false)];
61    while let Some((expr, within_navigation, within_aggregate)) = pending.pop() {
62        if within_aggregate && matches!(expr, BoundMatchExpr::Navigation(_)) {
63            return plan_err!(
64                "MATCH_RECOGNIZE source {} aggregates cannot contain navigation",
65                clause.name()
66            );
67        }
68        if within_navigation && matches!(expr, BoundMatchExpr::Navigation(_)) {
69            return plan_err!(
70                "MATCH_RECOGNIZE source {} navigation cannot nest this navigation call; only PREV/NEXT may directly wrap FIRST/LAST",
71                clause.name()
72            );
73        }
74
75        match expr {
76            BoundMatchExpr::InputExpr(expr) => {
77                if !clause.allows_input_expr_windows()
78                    && input_expr_contains_window(expr)?
79                {
80                    return plan_err!(
81                        "MATCH_RECOGNIZE source {} expression cannot contain window expressions",
82                        clause.name()
83                    );
84                }
85            }
86            BoundMatchExpr::PatternField(_)
87            | BoundMatchExpr::Metadata(_)
88            | BoundMatchExpr::Navigation(_)
89            | BoundMatchExpr::Aggregate(_)
90                if !clause.allows_row_pattern_constructs() =>
91            {
92                return plan_err!(
93                    "MATCH_RECOGNIZE source {} expression cannot contain MATCH_RECOGNIZE constructs",
94                    clause.name()
95                );
96            }
97            BoundMatchExpr::Aggregate(aggregate) => {
98                if let Some(symbol) = &aggregate.wildcard_symbol {
99                    if !aggregate.name.eq_ignore_ascii_case("count") {
100                        return plan_err!(
101                            "MATCH_RECOGNIZE aggregate '{}({symbol}.*)' is only supported for COUNT",
102                            aggregate.name
103                        );
104                    }
105                    if !aggregate.args.is_empty() {
106                        return plan_err!(
107                            "MATCH_RECOGNIZE aggregate 'COUNT({symbol}.*)' cannot also contain positional arguments"
108                        );
109                    }
110                    if aggregate.distinct {
111                        return plan_err!(
112                            "MATCH_RECOGNIZE aggregate 'COUNT(DISTINCT {symbol}.*)' is not supported"
113                        );
114                    }
115                }
116            }
117            _ => {}
118        }
119
120        let child_start = pending.len();
121        if let BoundMatchExpr::Navigation(
122            MatchNavigation::Prev {
123                expr: inner,
124                offset,
125                default,
126            }
127            | MatchNavigation::Next {
128                expr: inner,
129                offset,
130                default,
131            },
132        ) = expr
133            && let BoundMatchExpr::Navigation(
134                MatchNavigation::First {
135                    expr: inner_expr,
136                    offset: inner_offset,
137                }
138                | MatchNavigation::Last {
139                    expr: inner_expr,
140                    offset: inner_offset,
141                },
142            ) = inner.as_ref()
143        {
144            // Compound navigation: physical PREV/NEXT directly wrapping logical
145            // FIRST/LAST. Neither operand may contain any further navigation.
146            pending.push((inner_expr, true, within_aggregate));
147            if let Some(inner_offset) = inner_offset {
148                pending.push((inner_offset, true, within_aggregate));
149            }
150            if let Some(offset) = offset {
151                pending.push((offset, true, within_aggregate));
152            }
153            if let Some(default) = default {
154                pending.push((default, true, within_aggregate));
155            }
156        } else {
157            let within_navigation =
158                within_navigation || matches!(expr, BoundMatchExpr::Navigation(_));
159            // Keep aggregate validation ahead of lowering, which can erase self LAST
160            // inside aggregate arguments, FILTER, or ORDER BY.
161            let within_aggregate =
162                within_aggregate || matches!(expr, BoundMatchExpr::Aggregate(_));
163            expr.try_for_each_child(|child| {
164                pending.push((child, within_navigation, within_aggregate));
165                Ok(())
166            })?;
167        }
168        pending[child_start..].reverse();
169    }
170    Ok(())
171}
172
173fn input_expr_contains_window(expr: &Expr) -> Result<bool> {
174    let mut contains_window = false;
175    expr.apply(|node| {
176        if matches!(node, Expr::WindowFunction(_)) {
177            contains_window = true;
178            return Ok(TreeNodeRecursion::Stop);
179        }
180        Ok(TreeNodeRecursion::Continue)
181    })?;
182    Ok(contains_window)
183}
184
185pub(super) fn validate_input_expr(
186    input_schema: &DFSchema,
187    pattern_symbols: &CanonicalSymbolMap,
188    expr: &Expr,
189) -> Result<()> {
190    expr.apply(|node| {
191        classify_input_expr_node(input_schema, pattern_symbols, node)?;
192        Ok(TreeNodeRecursion::Continue)
193    })?;
194    Ok(())
195}
196
197fn classify_input_expr_node(
198    input_schema: &DFSchema,
199    pattern_symbols: &CanonicalSymbolMap,
200    expr: &Expr,
201) -> Result<()> {
202    match expr {
203        Expr::Alias(alias) => {
204            reject_reserved_identifier("InputExpr alias", &alias.name)?;
205            if let Some(relation) = &alias.relation {
206                reject_reserved_relation("InputExpr alias qualifier", relation)?;
207            }
208            Ok(())
209        }
210        Expr::Column(column) => {
211            validate_column_identifiers("InputExpr column", column)?;
212            if let Some(relation) = &column.relation
213                && pattern_symbols.contains_relation(relation)
214                && input_schema.qualified_field_from_column(column).is_err()
215            {
216                return plan_err!(
217                    "MATCH_RECOGNIZE source InputExpr cannot use pattern-qualified column '{}.{}'; use BoundMatchExpr::PatternField",
218                    relation.table(),
219                    column.name()
220                );
221            }
222            Ok(())
223        }
224        Expr::ScalarVariable(_, _) => {
225            plan_err!("MATCH_RECOGNIZE source InputExpr cannot contain scalar variables")
226        }
227        Expr::Literal(_, metadata) => {
228            if metadata.is_some() {
229                return plan_err!(
230                    "MATCH_RECOGNIZE source InputExpr cannot contain literal field metadata"
231                );
232            }
233            Ok(())
234        }
235        Expr::BinaryExpr(_) => Ok(()),
236        Expr::Like(_) | Expr::SimilarTo(_) => Ok(()),
237        Expr::Not(_)
238        | Expr::IsNotNull(_)
239        | Expr::IsNull(_)
240        | Expr::IsTrue(_)
241        | Expr::IsFalse(_)
242        | Expr::IsUnknown(_)
243        | Expr::IsNotTrue(_)
244        | Expr::IsNotFalse(_)
245        | Expr::IsNotUnknown(_)
246        | Expr::Negative(_)
247        | Expr::Between(_)
248        | Expr::Case(_)
249        | Expr::Cast(_)
250        | Expr::TryCast(_)
251        | Expr::InList(_) => Ok(()),
252        Expr::ScalarFunction(function) => {
253            let name = function.name();
254            reject_reserved_identifier("InputExpr scalar function", name)?;
255            if crate::planning::define::is_metadata_placeholder(&function.func) {
256                return plan_err!(
257                    "MATCH_RECOGNIZE source InputExpr cannot contain metadata placeholder '{}'; use BoundMatchExpr::Metadata",
258                    name
259                );
260            }
261            Ok(())
262        }
263        Expr::AggregateFunction(_) => {
264            plan_err!(
265                "MATCH_RECOGNIZE source InputExpr cannot contain aggregate expressions; use BoundMatchExpr::Aggregate"
266            )
267        }
268        Expr::WindowFunction(window) => {
269            reject_reserved_identifier("InputExpr window function", window.fun.name())?;
270            if crate::planning::define::is_navigation_window(&window.fun) {
271                return plan_err!(
272                    "MATCH_RECOGNIZE source InputExpr cannot contain MATCH_RECOGNIZE window function '{}'; use structured navigation source expressions",
273                    window.fun.name()
274                );
275            }
276            Ok(())
277        }
278        Expr::Exists(_)
279        | Expr::InSubquery(_)
280        | Expr::SetComparison(_)
281        | Expr::ScalarSubquery(_) => {
282            plan_err!("MATCH_RECOGNIZE source InputExpr cannot contain subqueries")
283        }
284        #[allow(deprecated)]
285        Expr::Wildcard { .. } => {
286            plan_err!("MATCH_RECOGNIZE source InputExpr cannot contain wildcards")
287        }
288        Expr::GroupingSet(_) => {
289            plan_err!("MATCH_RECOGNIZE source InputExpr cannot contain grouping sets")
290        }
291        Expr::Placeholder(_) => {
292            plan_err!("MATCH_RECOGNIZE source InputExpr cannot contain placeholders")
293        }
294        Expr::OuterReferenceColumn(_, _) => {
295            plan_err!(
296                "MATCH_RECOGNIZE source InputExpr cannot contain outer reference columns"
297            )
298        }
299        Expr::Unnest(_) => {
300            plan_err!("MATCH_RECOGNIZE source InputExpr cannot contain UNNEST")
301        }
302        Expr::HigherOrderFunction(_) | Expr::Lambda(_) | Expr::LambdaVariable(_) => {
303            plan_err!(
304                "MATCH_RECOGNIZE source InputExpr cannot contain higher-order or lambda expressions"
305            )
306        }
307    }
308}
309pub(super) fn validate_pattern_symbols_and_quantifiers(
310    spec: &BoundMatchSpec,
311) -> Result<()> {
312    for symbol in &spec.symbols {
313        reject_reserved_identifier("pattern symbol", symbol)?;
314    }
315    validate_source_pattern_quantifiers(&spec.pattern)
316}
317
318/// Possessive forms encode proven optimizer decisions, not source semantics.
319/// Reject them before lowering so composite, nullable, or anchored caller
320/// patterns cannot rely on the runtime's narrower row-local suppression rule.
321/// Also reject zero upper-bound or inverted quantifiers (`{0}`, `{0,0}`, `{,0}`,
322/// `{m,n}` with `m > n`).
323pub(crate) fn validate_source_pattern_quantifiers(pattern: &Pattern) -> Result<()> {
324    match pattern {
325        Pattern::Repetition(inner, quantifier) => {
326            if quantifier.is_possessive() {
327                return plan_err!(
328                    "MATCH_RECOGNIZE possessive quantifiers are internal optimizer markers and cannot be supplied in a source pattern"
329                );
330            }
331            let bounds = quantifier.bounds();
332            if let Some(max) = bounds.max {
333                if bounds.min > max {
334                    return plan_err!(
335                        "MATCH_RECOGNIZE pattern quantifier lower bound {} exceeds upper bound {}",
336                        bounds.min,
337                        max
338                    );
339                }
340                if max == 0 {
341                    return plan_err!(
342                        "MATCH_RECOGNIZE pattern quantifier upper bound must be greater than zero"
343                    );
344                }
345            }
346            validate_source_pattern_quantifiers(inner)
347        }
348        Pattern::Group(inner) => validate_source_pattern_quantifiers(inner),
349        Pattern::Concat(patterns) | Pattern::Alternation(patterns) => {
350            for pattern in patterns {
351                validate_source_pattern_quantifiers(pattern)?;
352            }
353            Ok(())
354        }
355        Pattern::Symbol(_) | Pattern::Exclude(_) | Pattern::Permute(_) => Ok(()),
356    }
357}
358
359/// Reject pattern symbols that coincide with an input table qualifier, ignoring
360/// ASCII case. The first collision in `symbols` determines the diagnostic.
361///
362/// Retained for SemVer compatibility with `0.56.0`; `MATCH_RECOGNIZE` now
363/// resolves pattern variables and input table qualifiers per clause.
364#[deprecated(
365    since = "0.56.1",
366    note = "MATCH_RECOGNIZE now resolves pattern variables and input table qualifiers per clause; this helper is no longer called by the planner"
367)]
368pub fn validate_pattern_qualifiers<'a>(
369    input_schema: &DFSchema,
370    symbols: impl IntoIterator<Item = &'a str>,
371) -> Result<()> {
372    let input_qualifiers = input_schema
373        .iter()
374        .filter_map(|(qualifier, _)| qualifier)
375        .map(|qualifier| qualifier.table().to_ascii_lowercase())
376        .collect::<BTreeSet<_>>();
377    for symbol in symbols {
378        if input_qualifiers.contains(&symbol.to_ascii_lowercase()) {
379            return plan_err!(
380                "MATCH_RECOGNIZE pattern symbol '{}' is ambiguous with an input qualifier; rename the pattern symbol or table alias",
381                symbol
382            );
383        }
384    }
385    Ok(())
386}
387
388pub(super) fn validate_input_schema_identifiers(input_schema: &DFSchema) -> Result<()> {
389    for (qualifier, field) in input_schema.iter() {
390        validate_arrow_field_identifiers(field)?;
391        if let Some(qualifier) = qualifier {
392            reject_reserved_relation("source input qualifier", qualifier)?;
393        }
394    }
395    Ok(())
396}
397
398fn validate_arrow_field_identifiers(field: &Field) -> Result<()> {
399    reject_reserved_input_column_identifier(field.name())?;
400    validate_data_type_identifiers(field.data_type())
401}
402
403fn validate_data_type_identifiers(data_type: &DataType) -> Result<()> {
404    match data_type {
405        DataType::List(field)
406        | DataType::ListView(field)
407        | DataType::LargeList(field)
408        | DataType::LargeListView(field)
409        | DataType::FixedSizeList(field, _)
410        | DataType::Map(field, _) => validate_arrow_field_identifiers(field),
411        DataType::Struct(fields) => {
412            for field in fields {
413                validate_arrow_field_identifiers(field)?;
414            }
415            Ok(())
416        }
417        DataType::Dictionary(_, value_type) => validate_data_type_identifiers(value_type),
418        DataType::RunEndEncoded(run_ends, values) => {
419            validate_arrow_field_identifiers(run_ends)?;
420            validate_arrow_field_identifiers(values)
421        }
422        _ => Ok(()),
423    }
424}
425
426pub(super) fn validate_column_identifiers(context: &str, column: &Column) -> Result<()> {
427    reject_reserved_identifier(context, column.name())?;
428    if let Some(relation) = &column.relation {
429        reject_reserved_relation(context, relation)?;
430    }
431    Ok(())
432}
433
434fn reject_reserved_relation(context: &str, relation: &TableReference) -> Result<()> {
435    for part in [
436        relation.catalog(),
437        relation.schema(),
438        Some(relation.table()),
439    ]
440    .into_iter()
441    .flatten()
442    {
443        reject_reserved_identifier(context, part)?;
444    }
445    Ok(())
446}
447
448pub(super) fn reject_reserved_identifier(context: &str, name: &str) -> Result<()> {
449    if is_reserved_internal_column_name(name) {
450        return plan_err!(
451            "MATCH_RECOGNIZE source {context} '{}' uses a reserved internal prefix",
452            name
453        );
454    }
455    Ok(())
456}
457
458fn reject_reserved_input_column_identifier(name: &str) -> Result<()> {
459    if is_reserved_internal_column_name(name) {
460        return plan_err!(
461            "MATCH_RECOGNIZE input column '{}' uses reserved internal prefix '__mr_'; alias the column before MATCH_RECOGNIZE",
462            name
463        );
464    }
465    Ok(())
466}
467
468pub(super) fn is_mr_reserved_function_name(name: &str) -> bool {
469    // Function names are registry keys; noncanonical quoted spellings can name
470    // distinct user functions. Reserved `__mr_*` identifiers are rejected
471    // before this check, and direct placeholder implementations are checked
472    // after binding.
473    matches!(
474        name,
475        "classifier"
476            | "match_number"
477            | "match_sequence_number"
478            | "excluded"
479            | "first"
480            | "last"
481            | "prev"
482            | "next"
483    )
484}