Skip to main content

datafusion_match_recognize/core/
spec.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//! Generic source-level MATCH_RECOGNIZE specification.
17//!
18//! Source expressions use a generic type parameter. SQL and Substrait adapters
19//! can therefore use the same specification without exposing their own syntax
20//! tree types to this crate.
21
22use std::collections::{BTreeMap, BTreeSet};
23use std::error::Error;
24use std::fmt::{self, Display, Formatter};
25
26use crate::core::pattern::{AfterMatchSkip, Pattern, RowsPerMatch, Symbol};
27
28/// Result type for source-level `MATCH_RECOGNIZE` specification validation.
29pub type MatchRecognizeSpecResult<T> = Result<T, MatchRecognizeSpecError>;
30
31/// Source-level `MATCH_RECOGNIZE` specification shared by importers.
32#[derive(Clone, Debug, PartialEq, Eq, Hash)]
33pub struct MatchRecognizeSpec<E> {
34    /// PARTITION BY expressions.
35    pub partition_by: Vec<E>,
36    /// ORDER BY expressions and sort options.
37    pub order_by: Vec<MatchRecognizeSortExpr<E>>,
38    /// ONE ROW PER MATCH / ALL ROWS PER MATCH source output mode.
39    pub source_rows_per_match: RowsPerMatch,
40    /// AFTER MATCH SKIP behavior.
41    pub after_match_skip: AfterMatchSkip,
42    /// Source pattern AST.
43    pub pattern: Pattern,
44    /// Complete declared pattern-symbol domain in importer order.
45    ///
46    /// Planning canonicalizes case-insensitive names into deterministic order
47    /// before assigning numeric identifiers.
48    pub symbols: Vec<String>,
49    /// DEFINE predicates keyed by symbol.
50    pub definitions: Vec<MatchRecognizeDefinition<E>>,
51    /// MEASURES expressions.
52    pub measures: Vec<MatchRecognizeMeasure<E>>,
53    /// How the consumer should build the output projection.
54    pub output: MatchRecognizeOutputContract<E>,
55}
56
57impl<E> MatchRecognizeSpec<E> {
58    /// Validate and return a source-level spec.
59    pub fn try_new(self) -> MatchRecognizeSpecResult<Self> {
60        self.validate()?;
61        Ok(self)
62    }
63
64    /// Check the symbol and name rules for an unbound source specification.
65    pub fn validate(&self) -> MatchRecognizeSpecResult<()> {
66        let symbols = symbol_map(&self.symbols)?;
67        validate_pattern_symbols(&self.pattern, &symbols)?;
68        validate_definitions(&self.definitions, &symbols)?;
69        validate_skip_target(&self.after_match_skip, &symbols)?;
70        validate_measures(&self.measures)?;
71        self.output.validate()?;
72        Ok(())
73    }
74}
75
76/// Source-level ORDER BY expression and sort options.
77#[derive(Clone, Debug, PartialEq, Eq, Hash)]
78pub struct MatchRecognizeSortExpr<E> {
79    /// Expression that produces the sort key.
80    pub expr: E,
81    /// Sort direction for this key.
82    pub direction: MatchRecognizeSortDirection,
83    /// Placement of null keys.
84    pub null_ordering: MatchRecognizeNullOrdering,
85}
86
87/// Sort direction for a source-level ORDER BY expression.
88#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
89pub enum MatchRecognizeSortDirection {
90    /// Ascending order.
91    Asc,
92    /// Descending order.
93    Desc,
94}
95
96/// Null ordering for a source-level ORDER BY expression.
97#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
98pub enum MatchRecognizeNullOrdering {
99    /// Nulls precede non-null values.
100    First,
101    /// Nulls follow non-null values.
102    Last,
103}
104
105/// DEFINE predicate for a single pattern symbol.
106#[derive(Clone, Debug, PartialEq, Eq, Hash)]
107pub struct MatchRecognizeDefinition<E> {
108    /// Declared pattern-symbol name, matched case-insensitively.
109    pub symbol: String,
110    /// Boolean condition for rows assigned to `symbol`.
111    pub predicate: E,
112}
113
114/// MEASURES expression.
115#[derive(Clone, Debug, PartialEq, Eq, Hash)]
116pub struct MatchRecognizeMeasure<E> {
117    /// Output name; validation rejects `None` in a completed specification.
118    pub name: Option<String>,
119    /// Expression evaluated for this measure.
120    pub expression: E,
121}
122
123/// Describes the output of a source-level `MATCH_RECOGNIZE` specification.
124#[derive(Clone, Debug, PartialEq, Eq, Hash)]
125pub enum MatchRecognizeOutputContract<E> {
126    /// Output is derived by the consumer from source rows, metadata, measures,
127    /// and source schema.
128    Derived,
129    /// Output is exactly the provided named expression list.
130    ExplicitNamedExpressions(Vec<MatchRecognizeNamedExpression<E>>),
131}
132
133impl<E> MatchRecognizeOutputContract<E> {
134    fn validate(&self) -> Result<(), MatchRecognizeSpecError> {
135        match self {
136            Self::Derived => Ok(()),
137            Self::ExplicitNamedExpressions(expressions) => {
138                let mut seen = BTreeSet::new();
139                for expr in expressions {
140                    let key = normalize_name(&expr.name);
141                    if !seen.insert(key) {
142                        return Err(MatchRecognizeSpecError::DuplicateOutputName {
143                            name: expr.name.clone(),
144                        });
145                    }
146                }
147                Ok(())
148            }
149        }
150    }
151}
152
153/// Named expression used when the output is listed explicitly.
154#[derive(Clone, Debug, PartialEq, Eq, Hash)]
155pub struct MatchRecognizeNamedExpression<E> {
156    /// Exact output field name.
157    pub name: String,
158    /// Expression that produces the field.
159    pub expression: E,
160}
161
162/// Validation error for a source-level MATCH_RECOGNIZE specification.
163#[derive(Clone, Debug, PartialEq, Eq)]
164pub enum MatchRecognizeSpecError {
165    /// The declared symbol list contains the same case-insensitive name twice.
166    DuplicateSymbol {
167        /// Repeated spelling from the declared symbol list.
168        symbol: String,
169    },
170    /// The pattern contains two spellings of one case-insensitive symbol name.
171    DuplicatePatternSymbol {
172        /// Conflicting spelling encountered in the pattern.
173        symbol: String,
174        /// First spelling encountered in the pattern.
175        previous: String,
176    },
177    /// The declared symbol list and symbols referenced by the pattern differ.
178    PatternSymbolsMismatch {
179        /// Declared symbols not referenced by the pattern.
180        missing_from_pattern: Vec<String>,
181        /// Pattern symbols absent from the declared list.
182        unknown_in_pattern: Vec<String>,
183    },
184    /// More than one `DEFINE` entry targets the same case-insensitive symbol.
185    DuplicateDefinition {
186        /// Repeated definition target.
187        symbol: String,
188    },
189    /// A `DEFINE` entry targets a symbol outside the declared domain.
190    UnknownDefinition {
191        /// Unknown definition target.
192        symbol: String,
193    },
194    /// `AFTER MATCH SKIP TO FIRST/LAST` targets an undeclared symbol.
195    UnknownSkipTarget {
196        /// Unknown skip target.
197        symbol: String,
198    },
199    /// A completed measure has no output name.
200    MissingMeasureName,
201    /// Two measures use the same case-insensitive output name.
202    DuplicateMeasureName {
203        /// Repeated measure name.
204        name: String,
205    },
206    /// Two explicitly listed outputs use the same case-insensitive name.
207    DuplicateOutputName {
208        /// Repeated output name.
209        name: String,
210    },
211}
212
213impl Display for MatchRecognizeSpecError {
214    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
215        match self {
216            Self::DuplicateSymbol { symbol } => {
217                write!(f, "duplicate MATCH_RECOGNIZE symbol: {symbol}")
218            }
219            Self::DuplicatePatternSymbol { symbol, previous } => write!(
220                f,
221                "MATCH_RECOGNIZE pattern symbol {symbol} conflicts with symbol {previous} by case-insensitive name"
222            ),
223            Self::PatternSymbolsMismatch {
224                missing_from_pattern,
225                unknown_in_pattern,
226            } => write!(
227                f,
228                "pattern symbols do not match declared symbols: missing_from_pattern={missing_from_pattern:?}, unknown_in_pattern={unknown_in_pattern:?}"
229            ),
230            Self::DuplicateDefinition { symbol } => {
231                write!(f, "duplicate DEFINE entry for symbol: {symbol}")
232            }
233            Self::UnknownDefinition { symbol } => {
234                write!(f, "DEFINE entry references unknown symbol: {symbol}")
235            }
236            Self::UnknownSkipTarget { symbol } => {
237                write!(f, "AFTER MATCH SKIP references unknown symbol: {symbol}")
238            }
239            Self::MissingMeasureName => {
240                write!(f, "MEASURES expression requires a name")
241            }
242            Self::DuplicateMeasureName { name } => {
243                write!(f, "duplicate MEASURES name: {name}")
244            }
245            Self::DuplicateOutputName { name } => {
246                write!(f, "duplicate explicit output name: {name}")
247            }
248        }
249    }
250}
251
252impl Error for MatchRecognizeSpecError {}
253
254fn symbol_map(symbols: &[String]) -> MatchRecognizeSpecResult<BTreeMap<String, String>> {
255    let mut seen = BTreeMap::new();
256    for symbol in symbols {
257        let key = normalize_name(symbol);
258        if seen.insert(key, symbol.clone()).is_some() {
259            return Err(MatchRecognizeSpecError::DuplicateSymbol {
260                symbol: symbol.clone(),
261            });
262        }
263    }
264    Ok(seen)
265}
266
267fn validate_pattern_symbols(
268    pattern: &Pattern,
269    symbols: &BTreeMap<String, String>,
270) -> MatchRecognizeSpecResult<()> {
271    let pattern_symbols = pattern_symbol_map(pattern)?;
272
273    let missing_from_pattern = symbols
274        .iter()
275        .filter(|(key, _)| !pattern_symbols.contains_key(*key))
276        .map(|(_, symbol)| symbol.clone())
277        .collect::<Vec<_>>();
278
279    let unknown_in_pattern = pattern_symbols
280        .iter()
281        .filter(|(key, _)| !symbols.contains_key(*key))
282        .map(|(_, symbol)| symbol.clone())
283        .collect::<Vec<_>>();
284
285    if missing_from_pattern.is_empty() && unknown_in_pattern.is_empty() {
286        Ok(())
287    } else {
288        Err(MatchRecognizeSpecError::PatternSymbolsMismatch {
289            missing_from_pattern,
290            unknown_in_pattern,
291        })
292    }
293}
294
295fn validate_definitions<E>(
296    definitions: &[MatchRecognizeDefinition<E>],
297    symbols: &BTreeMap<String, String>,
298) -> MatchRecognizeSpecResult<()> {
299    let mut seen = BTreeSet::new();
300    for definition in definitions {
301        let key = normalize_name(&definition.symbol);
302        if !symbols.contains_key(&key) {
303            return Err(MatchRecognizeSpecError::UnknownDefinition {
304                symbol: definition.symbol.clone(),
305            });
306        }
307        if !seen.insert(key) {
308            return Err(MatchRecognizeSpecError::DuplicateDefinition {
309                symbol: definition.symbol.clone(),
310            });
311        }
312    }
313    Ok(())
314}
315
316fn validate_skip_target(
317    after_match_skip: &AfterMatchSkip,
318    symbols: &BTreeMap<String, String>,
319) -> MatchRecognizeSpecResult<()> {
320    let target = match after_match_skip {
321        AfterMatchSkip::ToFirst(symbol) | AfterMatchSkip::ToLast(symbol) => symbol,
322        AfterMatchSkip::PastLastRow | AfterMatchSkip::ToNextRow => return Ok(()),
323    };
324
325    if symbols.contains_key(&normalize_name(target)) {
326        Ok(())
327    } else {
328        Err(MatchRecognizeSpecError::UnknownSkipTarget {
329            symbol: target.clone(),
330        })
331    }
332}
333
334fn validate_measures<E>(
335    measures: &[MatchRecognizeMeasure<E>],
336) -> MatchRecognizeSpecResult<()> {
337    let mut seen = BTreeSet::new();
338    for measure in measures {
339        let Some(name) = &measure.name else {
340            return Err(MatchRecognizeSpecError::MissingMeasureName);
341        };
342
343        let key = normalize_name(name);
344        if !seen.insert(key) {
345            return Err(MatchRecognizeSpecError::DuplicateMeasureName {
346                name: name.clone(),
347            });
348        }
349    }
350    Ok(())
351}
352
353fn pattern_symbol_map(
354    pattern: &Pattern,
355) -> MatchRecognizeSpecResult<BTreeMap<String, String>> {
356    let mut pending = vec![pattern];
357    let mut symbols: BTreeMap<String, String> = BTreeMap::new();
358    while let Some(node) = pending.pop() {
359        let leaf_symbols = match node {
360            Pattern::Symbol(symbol) | Pattern::Exclude(symbol) => {
361                std::slice::from_ref(symbol)
362            }
363            Pattern::Permute(permuted) => permuted.as_slice(),
364            Pattern::Concat(parts) | Pattern::Alternation(parts) => {
365                pending.extend(parts.iter().rev());
366                continue;
367            }
368            Pattern::Group(inner) | Pattern::Repetition(inner, _) => {
369                pending.push(inner);
370                continue;
371            }
372        };
373        for symbol in leaf_symbols {
374            if let Symbol::Named(name) = symbol {
375                let key = normalize_name(name);
376                if let Some(previous) = symbols.get(&key) {
377                    if previous != name {
378                        return Err(MatchRecognizeSpecError::DuplicatePatternSymbol {
379                            symbol: name.clone(),
380                            previous: previous.clone(),
381                        });
382                    }
383                } else {
384                    symbols.insert(key, name.clone());
385                }
386            }
387        }
388    }
389    Ok(symbols)
390}
391
392fn normalize_name(name: &str) -> String {
393    name.to_ascii_lowercase()
394}
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399    use crate::core::pattern::{EmptyMatchesMode, RepetitionQuantifier};
400
401    type TestSpec = MatchRecognizeSpec<&'static str>;
402
403    fn valid_spec() -> TestSpec {
404        MatchRecognizeSpec {
405            partition_by: vec!["account_id"],
406            order_by: vec![MatchRecognizeSortExpr {
407                expr: "event_time",
408                direction: MatchRecognizeSortDirection::Asc,
409                null_ordering: MatchRecognizeNullOrdering::Last,
410            }],
411            source_rows_per_match: RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
412            after_match_skip: AfterMatchSkip::ToLast("B".to_string()),
413            pattern: Pattern::Concat(vec![
414                Pattern::Repetition(
415                    Box::new(Pattern::Symbol(Symbol::Named("A".to_string()))),
416                    RepetitionQuantifier::OneOrMore,
417                ),
418                Pattern::Symbol(Symbol::Named("B".to_string())),
419            ]),
420            symbols: vec!["A".to_string(), "B".to_string()],
421            definitions: vec![
422                MatchRecognizeDefinition {
423                    symbol: "A".to_string(),
424                    predicate: "price > 0",
425                },
426                MatchRecognizeDefinition {
427                    symbol: "B".to_string(),
428                    predicate: "price < prev(price)",
429                },
430            ],
431            measures: vec![MatchRecognizeMeasure {
432                name: Some("last_price".to_string()),
433                expression: "last(price)",
434            }],
435            output: MatchRecognizeOutputContract::Derived,
436        }
437    }
438
439    #[test]
440    fn validate_rejects_case_insensitive_duplicate_symbols() {
441        let mut spec = valid_spec();
442        spec.symbols = vec!["A".to_string(), "a".to_string()];
443
444        assert_eq!(
445            spec.validate(),
446            Err(MatchRecognizeSpecError::DuplicateSymbol {
447                symbol: "a".to_string()
448            })
449        );
450    }
451
452    #[test]
453    fn validate_requires_pattern_symbols_to_match_declared_symbols() {
454        let mut spec = valid_spec();
455        spec.symbols = vec!["A".to_string(), "C".to_string()];
456
457        assert_eq!(
458            spec.validate(),
459            Err(MatchRecognizeSpecError::PatternSymbolsMismatch {
460                missing_from_pattern: vec!["C".to_string()],
461                unknown_in_pattern: vec!["B".to_string()],
462            })
463        );
464    }
465
466    #[test]
467    fn validate_allows_repeated_pattern_symbol_occurrences() {
468        let mut spec = valid_spec();
469        spec.pattern = Pattern::Concat(vec![
470            Pattern::Symbol(Symbol::Named("A".to_string())),
471            Pattern::Symbol(Symbol::Named("B".to_string())),
472            Pattern::Symbol(Symbol::Named("A".to_string())),
473        ]);
474
475        assert_eq!(spec.validate(), Ok(()));
476    }
477
478    #[test]
479    fn validate_rejects_case_insensitive_pattern_symbol_conflicts() {
480        let mut spec = valid_spec();
481        spec.pattern = Pattern::Concat(vec![
482            Pattern::Symbol(Symbol::Named("a".to_string())),
483            Pattern::Symbol(Symbol::Named("A".to_string())),
484            Pattern::Symbol(Symbol::Named("B".to_string())),
485        ]);
486
487        assert_eq!(
488            spec.validate(),
489            Err(MatchRecognizeSpecError::DuplicatePatternSymbol {
490                symbol: "A".to_string(),
491                previous: "a".to_string(),
492            })
493        );
494    }
495
496    #[test]
497    fn validate_rejects_duplicate_definitions() {
498        let mut spec = valid_spec();
499        spec.definitions.push(MatchRecognizeDefinition {
500            symbol: "a".to_string(),
501            predicate: "volume > 10",
502        });
503
504        assert_eq!(
505            spec.validate(),
506            Err(MatchRecognizeSpecError::DuplicateDefinition {
507                symbol: "a".to_string()
508            })
509        );
510    }
511
512    #[test]
513    fn validate_rejects_unknown_definition_symbol() {
514        let mut spec = valid_spec();
515        spec.definitions.push(MatchRecognizeDefinition {
516            symbol: "C".to_string(),
517            predicate: "volume > 10",
518        });
519
520        assert_eq!(
521            spec.validate(),
522            Err(MatchRecognizeSpecError::UnknownDefinition {
523                symbol: "C".to_string()
524            })
525        );
526    }
527
528    #[test]
529    fn validate_rejects_unknown_skip_target() {
530        let mut spec = valid_spec();
531        spec.after_match_skip = AfterMatchSkip::ToFirst("C".to_string());
532
533        assert_eq!(
534            spec.validate(),
535            Err(MatchRecognizeSpecError::UnknownSkipTarget {
536                symbol: "C".to_string()
537            })
538        );
539    }
540
541    #[test]
542    fn validate_rejects_missing_measure_name_when_required() {
543        let mut spec = valid_spec();
544        spec.output = MatchRecognizeOutputContract::ExplicitNamedExpressions(vec![
545            MatchRecognizeNamedExpression {
546                name: "out_price".to_string(),
547                expression: "last_price",
548            },
549        ]);
550        spec.measures = vec![MatchRecognizeMeasure {
551            name: None,
552            expression: "last(price)",
553        }];
554
555        assert_eq!(
556            spec.validate(),
557            Err(MatchRecognizeSpecError::MissingMeasureName)
558        );
559    }
560
561    #[test]
562    fn specification_rejects_duplicate_measure_and_explicit_output_names() {
563        let named = |name: &str, expression| MatchRecognizeNamedExpression {
564            name: name.into(),
565            expression,
566        };
567        for output in [
568            MatchRecognizeOutputContract::Derived,
569            MatchRecognizeOutputContract::ExplicitNamedExpressions(vec![named(
570                "out_price",
571                "last_price",
572            )]),
573        ] {
574            let mut spec = valid_spec();
575            spec.output = output;
576            spec.measures = vec![
577                MatchRecognizeMeasure {
578                    name: Some("m".into()),
579                    expression: "last(price)",
580                },
581                MatchRecognizeMeasure {
582                    name: Some("M".into()),
583                    expression: "first(price)",
584                },
585            ];
586            assert_eq!(
587                spec.validate(),
588                Err(MatchRecognizeSpecError::DuplicateMeasureName { name: "M".into() })
589            );
590        }
591        let mut spec = valid_spec();
592        spec.output = MatchRecognizeOutputContract::ExplicitNamedExpressions(vec![
593            named("out_price", "last_price"),
594            named("OUT_PRICE", "first_price"),
595        ]);
596        assert_eq!(
597            spec.validate(),
598            Err(MatchRecognizeSpecError::DuplicateOutputName {
599                name: "OUT_PRICE".into()
600            })
601        );
602    }
603}