datafusion-match-recognize 0.55.0

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
// Licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! Generic source-level MATCH_RECOGNIZE specification.
//!
//! Source expressions use a generic type parameter. SQL and Substrait adapters
//! can therefore use the same specification without exposing their own syntax
//! tree types to this crate.

use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt::{self, Display, Formatter};

use crate::core::pattern::{AfterMatchSkip, Pattern, RowsPerMatch, Symbol};

/// Result type for source-level `MATCH_RECOGNIZE` specification validation.
pub type MatchRecognizeSpecResult<T> = Result<T, MatchRecognizeSpecError>;

/// Source-level `MATCH_RECOGNIZE` specification shared by importers.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchRecognizeSpec<E> {
    /// PARTITION BY expressions.
    pub partition_by: Vec<E>,
    /// ORDER BY expressions and sort options.
    pub order_by: Vec<MatchRecognizeSortExpr<E>>,
    /// ONE ROW PER MATCH / ALL ROWS PER MATCH source output mode.
    pub source_rows_per_match: RowsPerMatch,
    /// AFTER MATCH SKIP behavior.
    pub after_match_skip: AfterMatchSkip,
    /// Source pattern AST.
    pub pattern: Pattern,
    /// Complete declared pattern-symbol domain in importer order.
    ///
    /// Planning canonicalizes case-insensitive names into deterministic order
    /// before assigning numeric identifiers.
    pub symbols: Vec<String>,
    /// DEFINE predicates keyed by symbol.
    pub definitions: Vec<MatchRecognizeDefinition<E>>,
    /// MEASURES expressions.
    pub measures: Vec<MatchRecognizeMeasure<E>>,
    /// How the consumer should build the output projection.
    pub output: MatchRecognizeOutputContract<E>,
}

impl<E> MatchRecognizeSpec<E> {
    /// Validate and return a source-level spec.
    pub fn try_new(self) -> MatchRecognizeSpecResult<Self> {
        self.validate()?;
        Ok(self)
    }

    /// Check the symbol and name rules for an unbound source specification.
    pub fn validate(&self) -> MatchRecognizeSpecResult<()> {
        let symbols = symbol_map(&self.symbols)?;
        validate_pattern_symbols(&self.pattern, &symbols)?;
        validate_definitions(&self.definitions, &symbols)?;
        validate_skip_target(&self.after_match_skip, &symbols)?;
        validate_measures(&self.measures)?;
        self.output.validate()?;
        Ok(())
    }
}

/// Source-level ORDER BY expression and sort options.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchRecognizeSortExpr<E> {
    /// Expression that produces the sort key.
    pub expr: E,
    /// Sort direction for this key.
    pub direction: MatchRecognizeSortDirection,
    /// Placement of null keys.
    pub null_ordering: MatchRecognizeNullOrdering,
}

/// Sort direction for a source-level ORDER BY expression.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MatchRecognizeSortDirection {
    /// Ascending order.
    Asc,
    /// Descending order.
    Desc,
}

/// Null ordering for a source-level ORDER BY expression.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MatchRecognizeNullOrdering {
    /// Nulls precede non-null values.
    First,
    /// Nulls follow non-null values.
    Last,
}

/// DEFINE predicate for a single pattern symbol.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchRecognizeDefinition<E> {
    /// Declared pattern-symbol name, matched case-insensitively.
    pub symbol: String,
    /// Boolean condition for rows assigned to `symbol`.
    pub predicate: E,
}

/// MEASURES expression.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchRecognizeMeasure<E> {
    /// Output name; validation rejects `None` in a completed specification.
    pub name: Option<String>,
    /// Expression evaluated for this measure.
    pub expression: E,
}

/// Describes the output of a source-level `MATCH_RECOGNIZE` specification.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MatchRecognizeOutputContract<E> {
    /// Output is derived by the consumer from source rows, metadata, measures,
    /// and source schema.
    Derived,
    /// Output is exactly the provided named expression list.
    ExplicitNamedExpressions(Vec<MatchRecognizeNamedExpression<E>>),
}

impl<E> MatchRecognizeOutputContract<E> {
    fn validate(&self) -> Result<(), MatchRecognizeSpecError> {
        match self {
            Self::Derived => Ok(()),
            Self::ExplicitNamedExpressions(expressions) => {
                let mut seen = BTreeSet::new();
                for expr in expressions {
                    let key = normalize_name(&expr.name);
                    if !seen.insert(key) {
                        return Err(MatchRecognizeSpecError::DuplicateOutputName {
                            name: expr.name.clone(),
                        });
                    }
                }
                Ok(())
            }
        }
    }
}

/// Named expression used when the output is listed explicitly.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchRecognizeNamedExpression<E> {
    /// Exact output field name.
    pub name: String,
    /// Expression that produces the field.
    pub expression: E,
}

/// Validation error for a source-level MATCH_RECOGNIZE specification.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MatchRecognizeSpecError {
    /// The declared symbol list contains the same case-insensitive name twice.
    DuplicateSymbol {
        /// Repeated spelling from the declared symbol list.
        symbol: String,
    },
    /// The pattern contains two spellings of one case-insensitive symbol name.
    DuplicatePatternSymbol {
        /// Conflicting spelling encountered in the pattern.
        symbol: String,
        /// First spelling encountered in the pattern.
        previous: String,
    },
    /// The declared symbol list and symbols referenced by the pattern differ.
    PatternSymbolsMismatch {
        /// Declared symbols not referenced by the pattern.
        missing_from_pattern: Vec<String>,
        /// Pattern symbols absent from the declared list.
        unknown_in_pattern: Vec<String>,
    },
    /// More than one `DEFINE` entry targets the same case-insensitive symbol.
    DuplicateDefinition {
        /// Repeated definition target.
        symbol: String,
    },
    /// A `DEFINE` entry targets a symbol outside the declared domain.
    UnknownDefinition {
        /// Unknown definition target.
        symbol: String,
    },
    /// `AFTER MATCH SKIP TO FIRST/LAST` targets an undeclared symbol.
    UnknownSkipTarget {
        /// Unknown skip target.
        symbol: String,
    },
    /// A completed measure has no output name.
    MissingMeasureName,
    /// Two measures use the same case-insensitive output name.
    DuplicateMeasureName {
        /// Repeated measure name.
        name: String,
    },
    /// Two explicitly listed outputs use the same case-insensitive name.
    DuplicateOutputName {
        /// Repeated output name.
        name: String,
    },
}

impl Display for MatchRecognizeSpecError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::DuplicateSymbol { symbol } => {
                write!(f, "duplicate MATCH_RECOGNIZE symbol: {symbol}")
            }
            Self::DuplicatePatternSymbol { symbol, previous } => write!(
                f,
                "MATCH_RECOGNIZE pattern symbol {symbol} conflicts with symbol {previous} by case-insensitive name"
            ),
            Self::PatternSymbolsMismatch {
                missing_from_pattern,
                unknown_in_pattern,
            } => write!(
                f,
                "pattern symbols do not match declared symbols: missing_from_pattern={missing_from_pattern:?}, unknown_in_pattern={unknown_in_pattern:?}"
            ),
            Self::DuplicateDefinition { symbol } => {
                write!(f, "duplicate DEFINE entry for symbol: {symbol}")
            }
            Self::UnknownDefinition { symbol } => {
                write!(f, "DEFINE entry references unknown symbol: {symbol}")
            }
            Self::UnknownSkipTarget { symbol } => {
                write!(f, "AFTER MATCH SKIP references unknown symbol: {symbol}")
            }
            Self::MissingMeasureName => {
                write!(f, "MEASURES expression requires a name")
            }
            Self::DuplicateMeasureName { name } => {
                write!(f, "duplicate MEASURES name: {name}")
            }
            Self::DuplicateOutputName { name } => {
                write!(f, "duplicate explicit output name: {name}")
            }
        }
    }
}

impl Error for MatchRecognizeSpecError {}

fn symbol_map(symbols: &[String]) -> MatchRecognizeSpecResult<BTreeMap<String, String>> {
    let mut seen = BTreeMap::new();
    for symbol in symbols {
        let key = normalize_name(symbol);
        if seen.insert(key, symbol.clone()).is_some() {
            return Err(MatchRecognizeSpecError::DuplicateSymbol {
                symbol: symbol.clone(),
            });
        }
    }
    Ok(seen)
}

fn validate_pattern_symbols(
    pattern: &Pattern,
    symbols: &BTreeMap<String, String>,
) -> MatchRecognizeSpecResult<()> {
    let pattern_symbols = pattern_symbol_map(pattern)?;

    let missing_from_pattern = symbols
        .iter()
        .filter(|(key, _)| !pattern_symbols.contains_key(*key))
        .map(|(_, symbol)| symbol.clone())
        .collect::<Vec<_>>();

    let unknown_in_pattern = pattern_symbols
        .iter()
        .filter(|(key, _)| !symbols.contains_key(*key))
        .map(|(_, symbol)| symbol.clone())
        .collect::<Vec<_>>();

    if missing_from_pattern.is_empty() && unknown_in_pattern.is_empty() {
        Ok(())
    } else {
        Err(MatchRecognizeSpecError::PatternSymbolsMismatch {
            missing_from_pattern,
            unknown_in_pattern,
        })
    }
}

fn validate_definitions<E>(
    definitions: &[MatchRecognizeDefinition<E>],
    symbols: &BTreeMap<String, String>,
) -> MatchRecognizeSpecResult<()> {
    let mut seen = BTreeSet::new();
    for definition in definitions {
        let key = normalize_name(&definition.symbol);
        if !symbols.contains_key(&key) {
            return Err(MatchRecognizeSpecError::UnknownDefinition {
                symbol: definition.symbol.clone(),
            });
        }
        if !seen.insert(key) {
            return Err(MatchRecognizeSpecError::DuplicateDefinition {
                symbol: definition.symbol.clone(),
            });
        }
    }
    Ok(())
}

fn validate_skip_target(
    after_match_skip: &AfterMatchSkip,
    symbols: &BTreeMap<String, String>,
) -> MatchRecognizeSpecResult<()> {
    let target = match after_match_skip {
        AfterMatchSkip::ToFirst(symbol) | AfterMatchSkip::ToLast(symbol) => symbol,
        AfterMatchSkip::PastLastRow | AfterMatchSkip::ToNextRow => return Ok(()),
    };

    if symbols.contains_key(&normalize_name(target)) {
        Ok(())
    } else {
        Err(MatchRecognizeSpecError::UnknownSkipTarget {
            symbol: target.clone(),
        })
    }
}

fn validate_measures<E>(
    measures: &[MatchRecognizeMeasure<E>],
) -> MatchRecognizeSpecResult<()> {
    let mut seen = BTreeSet::new();
    for measure in measures {
        let Some(name) = &measure.name else {
            return Err(MatchRecognizeSpecError::MissingMeasureName);
        };

        let key = normalize_name(name);
        if !seen.insert(key) {
            return Err(MatchRecognizeSpecError::DuplicateMeasureName {
                name: name.clone(),
            });
        }
    }
    Ok(())
}

fn pattern_symbol_map(
    pattern: &Pattern,
) -> MatchRecognizeSpecResult<BTreeMap<String, String>> {
    let mut pending = vec![pattern];
    let mut symbols: BTreeMap<String, String> = BTreeMap::new();
    while let Some(node) = pending.pop() {
        let leaf_symbols = match node {
            Pattern::Symbol(symbol) | Pattern::Exclude(symbol) => {
                std::slice::from_ref(symbol)
            }
            Pattern::Permute(permuted) => permuted.as_slice(),
            Pattern::Concat(parts) | Pattern::Alternation(parts) => {
                pending.extend(parts.iter().rev());
                continue;
            }
            Pattern::Group(inner) | Pattern::Repetition(inner, _) => {
                pending.push(inner);
                continue;
            }
        };
        for symbol in leaf_symbols {
            if let Symbol::Named(name) = symbol {
                let key = normalize_name(name);
                if let Some(previous) = symbols.get(&key) {
                    if previous != name {
                        return Err(MatchRecognizeSpecError::DuplicatePatternSymbol {
                            symbol: name.clone(),
                            previous: previous.clone(),
                        });
                    }
                } else {
                    symbols.insert(key, name.clone());
                }
            }
        }
    }
    Ok(symbols)
}

fn normalize_name(name: &str) -> String {
    name.to_ascii_lowercase()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::pattern::{EmptyMatchesMode, RepetitionQuantifier};

    type TestSpec = MatchRecognizeSpec<&'static str>;

    fn valid_spec() -> TestSpec {
        MatchRecognizeSpec {
            partition_by: vec!["account_id"],
            order_by: vec![MatchRecognizeSortExpr {
                expr: "event_time",
                direction: MatchRecognizeSortDirection::Asc,
                null_ordering: MatchRecognizeNullOrdering::Last,
            }],
            source_rows_per_match: RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
            after_match_skip: AfterMatchSkip::ToLast("B".to_string()),
            pattern: Pattern::Concat(vec![
                Pattern::Repetition(
                    Box::new(Pattern::Symbol(Symbol::Named("A".to_string()))),
                    RepetitionQuantifier::OneOrMore,
                ),
                Pattern::Symbol(Symbol::Named("B".to_string())),
            ]),
            symbols: vec!["A".to_string(), "B".to_string()],
            definitions: vec![
                MatchRecognizeDefinition {
                    symbol: "A".to_string(),
                    predicate: "price > 0",
                },
                MatchRecognizeDefinition {
                    symbol: "B".to_string(),
                    predicate: "price < prev(price)",
                },
            ],
            measures: vec![MatchRecognizeMeasure {
                name: Some("last_price".to_string()),
                expression: "last(price)",
            }],
            output: MatchRecognizeOutputContract::Derived,
        }
    }

    #[test]
    fn validate_rejects_case_insensitive_duplicate_symbols() {
        let mut spec = valid_spec();
        spec.symbols = vec!["A".to_string(), "a".to_string()];

        assert_eq!(
            spec.validate(),
            Err(MatchRecognizeSpecError::DuplicateSymbol {
                symbol: "a".to_string()
            })
        );
    }

    #[test]
    fn validate_requires_pattern_symbols_to_match_declared_symbols() {
        let mut spec = valid_spec();
        spec.symbols = vec!["A".to_string(), "C".to_string()];

        assert_eq!(
            spec.validate(),
            Err(MatchRecognizeSpecError::PatternSymbolsMismatch {
                missing_from_pattern: vec!["C".to_string()],
                unknown_in_pattern: vec!["B".to_string()],
            })
        );
    }

    #[test]
    fn validate_allows_repeated_pattern_symbol_occurrences() {
        let mut spec = valid_spec();
        spec.pattern = Pattern::Concat(vec![
            Pattern::Symbol(Symbol::Named("A".to_string())),
            Pattern::Symbol(Symbol::Named("B".to_string())),
            Pattern::Symbol(Symbol::Named("A".to_string())),
        ]);

        assert_eq!(spec.validate(), Ok(()));
    }

    #[test]
    fn validate_rejects_case_insensitive_pattern_symbol_conflicts() {
        let mut spec = valid_spec();
        spec.pattern = Pattern::Concat(vec![
            Pattern::Symbol(Symbol::Named("a".to_string())),
            Pattern::Symbol(Symbol::Named("A".to_string())),
            Pattern::Symbol(Symbol::Named("B".to_string())),
        ]);

        assert_eq!(
            spec.validate(),
            Err(MatchRecognizeSpecError::DuplicatePatternSymbol {
                symbol: "A".to_string(),
                previous: "a".to_string(),
            })
        );
    }

    #[test]
    fn validate_rejects_duplicate_definitions() {
        let mut spec = valid_spec();
        spec.definitions.push(MatchRecognizeDefinition {
            symbol: "a".to_string(),
            predicate: "volume > 10",
        });

        assert_eq!(
            spec.validate(),
            Err(MatchRecognizeSpecError::DuplicateDefinition {
                symbol: "a".to_string()
            })
        );
    }

    #[test]
    fn validate_rejects_unknown_definition_symbol() {
        let mut spec = valid_spec();
        spec.definitions.push(MatchRecognizeDefinition {
            symbol: "C".to_string(),
            predicate: "volume > 10",
        });

        assert_eq!(
            spec.validate(),
            Err(MatchRecognizeSpecError::UnknownDefinition {
                symbol: "C".to_string()
            })
        );
    }

    #[test]
    fn validate_rejects_unknown_skip_target() {
        let mut spec = valid_spec();
        spec.after_match_skip = AfterMatchSkip::ToFirst("C".to_string());

        assert_eq!(
            spec.validate(),
            Err(MatchRecognizeSpecError::UnknownSkipTarget {
                symbol: "C".to_string()
            })
        );
    }

    #[test]
    fn validate_rejects_missing_measure_name_when_required() {
        let mut spec = valid_spec();
        spec.output = MatchRecognizeOutputContract::ExplicitNamedExpressions(vec![
            MatchRecognizeNamedExpression {
                name: "out_price".to_string(),
                expression: "last_price",
            },
        ]);
        spec.measures = vec![MatchRecognizeMeasure {
            name: None,
            expression: "last(price)",
        }];

        assert_eq!(
            spec.validate(),
            Err(MatchRecognizeSpecError::MissingMeasureName)
        );
    }

    #[test]
    fn specification_rejects_duplicate_measure_and_explicit_output_names() {
        let named = |name: &str, expression| MatchRecognizeNamedExpression {
            name: name.into(),
            expression,
        };
        for output in [
            MatchRecognizeOutputContract::Derived,
            MatchRecognizeOutputContract::ExplicitNamedExpressions(vec![named(
                "out_price",
                "last_price",
            )]),
        ] {
            let mut spec = valid_spec();
            spec.output = output;
            spec.measures = vec![
                MatchRecognizeMeasure {
                    name: Some("m".into()),
                    expression: "last(price)",
                },
                MatchRecognizeMeasure {
                    name: Some("M".into()),
                    expression: "first(price)",
                },
            ];
            assert_eq!(
                spec.validate(),
                Err(MatchRecognizeSpecError::DuplicateMeasureName { name: "M".into() })
            );
        }
        let mut spec = valid_spec();
        spec.output = MatchRecognizeOutputContract::ExplicitNamedExpressions(vec![
            named("out_price", "last_price"),
            named("OUT_PRICE", "first_price"),
        ]);
        assert_eq!(
            spec.validate(),
            Err(MatchRecognizeSpecError::DuplicateOutputName {
                name: "OUT_PRICE".into()
            })
        );
    }
}