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
604
605
606
607
608
609
610
611
612
613
614
615
616
// 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.

//! Share uniquely decodable prefixes after DEFINEs have become static Boolean columns.

use crate::core::{Pattern, RepetitionQuantifier, Symbol};

pub(super) fn factor(pattern: Pattern, disjoint: &[(String, String)]) -> Pattern {
    let visit = |part| factor(part, disjoint);
    match pattern {
        Pattern::Group(inner) => Pattern::Group(Box::new(visit(*inner))),
        Pattern::Concat(parts) => Pattern::Concat(parts.into_iter().map(visit).collect()),
        Pattern::Repetition(inner, quantifier) => {
            Pattern::Repetition(Box::new(visit(*inner)), quantifier)
        }
        Pattern::Alternation(branches) => {
            factor_adjacent(branches.into_iter().map(visit).collect(), disjoint)
        }
        other => other,
    }
}

fn parts(pattern: &Pattern) -> &[Pattern] {
    match pattern {
        Pattern::Concat(parts) => parts,
        other => std::slice::from_ref(other),
    }
}

fn into_parts(pattern: Pattern) -> Vec<Pattern> {
    match pattern {
        Pattern::Concat(parts) => parts,
        other => vec![other],
    }
}

fn concat(mut parts: Vec<Pattern>) -> Pattern {
    if parts.len() == 1 {
        parts.pop().expect("one fixed-prefix part")
    } else {
        Pattern::Concat(parts)
    }
}

/// Compare one nonempty classified word without expanding exact repetitions.
/// A fixed outer count is insufficient if its body still has length or branch
/// choices: sharing those choices could move them ahead of branch preference.
fn shared_word_start<'a>(left: &'a Pattern, right: &Pattern) -> Option<&'a str> {
    match (left, right) {
        (Pattern::Symbol(Symbol::Named(left)), Pattern::Symbol(Symbol::Named(right))) => {
            (left == right).then_some(left)
        }
        (Pattern::Group(left), _) => shared_word_start(left, right),
        (_, Pattern::Group(right)) => shared_word_start(left, right),
        (Pattern::Concat(left), Pattern::Concat(right)) if left.len() == right.len() => {
            let (first, rest) = left.split_first()?;
            let head = shared_word_start(first, &right[0])?;
            rest.iter()
                .zip(&right[1..])
                .all(|(a, b)| same_fixed_part(a, b))
                .then_some(head)
        }
        (Pattern::Repetition(left, lq), Pattern::Repetition(right, rq))
            if !lq.is_possessive()
                && !rq.is_possessive()
                && lq
                    .fixed_count()
                    .is_some_and(|n| n > 0 && rq.fixed_count() == Some(n)) =>
        {
            shared_word_start(left, right)
        }
        _ => None,
    }
}

fn same_fixed_part(left: &Pattern, right: &Pattern) -> bool {
    shared_word_start(left, right).is_some()
}

fn repeated_word(pattern: &Pattern) -> Option<(&Pattern, RepetitionQuantifier)> {
    match pattern {
        Pattern::Repetition(body, quantifier)
            if !quantifier.is_possessive()
                && quantifier
                    .max_repetitions()
                    .is_none_or(|max| max >= quantifier.min_repetitions())
                && same_fixed_part(body, body) =>
        {
            Some((body, quantifier.clone()))
        }
        other if same_fixed_part(other, other) => {
            Some((other, RepetitionQuantifier::Exactly(1)))
        }
        _ => None,
    }
}

fn remaining_word(
    body: &Pattern,
    quantifier: &RepetitionQuantifier,
    consumed: u32,
) -> Option<Pattern> {
    // The caller checked valid bounds and consumes only mandatory copies.
    let min = quantifier.min_repetitions() - consumed;
    let max = quantifier.max_repetitions().map(|max| max - consumed);
    if max == Some(0) {
        return None;
    }
    if min == 1 && max == Some(1) {
        return Some(body.clone());
    }
    let remaining = match max {
        Some(max) => RepetitionQuantifier::Range(min, max),
        None => RepetitionQuantifier::AtLeast(min),
    };
    let remaining = if quantifier.is_reluctant() {
        remaining
            .reluctant_variant()
            .expect("greedy remaining bounds")
    } else {
        remaining
    };
    Some(Pattern::Repetition(
        Box::new(body.clone()),
        remaining.normalized(),
    ))
}

fn share_mandatory_word(
    left: &Pattern,
    right: &Pattern,
) -> Option<(Pattern, Option<Pattern>, Option<Pattern>)> {
    let (left, lq) = repeated_word(left)?;
    let (right, rq) = repeated_word(right)?;
    let count = lq.min_repetitions().min(rq.min_repetitions());
    if count == 0 || !same_fixed_part(left, right) {
        return None;
    }
    let shared = if count == 1 {
        left.clone()
    } else {
        Pattern::Repetition(Box::new(left.clone()), RepetitionQuantifier::Exactly(count))
    };
    Some((
        shared,
        remaining_word(left, &lq, count),
        remaining_word(right, &rq, count),
    ))
}

/// Share both the repeat and its mandatory delimiter. An earlier successful
/// split would require the delimiter's first row to start another copy of the
/// same fixed word. Disjoint first symbols make that impossible, so moving the
/// split ahead of the ordered suffixes preserves their priority.
fn shared_delimited_word(
    left: &[Pattern],
    right: &[Pattern],
    disjoint: &[(String, String)],
) -> bool {
    let (
        [Pattern::Repetition(a, aq), a_end, ..],
        [Pattern::Repetition(b, bq), b_end, ..],
    ) = (left, right)
    else {
        return false;
    };
    if disjoint.is_empty()
        || aq != bq
        || aq.is_possessive()
        || aq
            .max_repetitions()
            .is_some_and(|max| max < aq.min_repetitions())
    {
        return false;
    }
    let (Some(start), Some(end)) =
        (shared_word_start(a, b), shared_word_start(a_end, b_end))
    else {
        return false;
    };
    disjoint.iter().any(|(l, r)| {
        (l.eq_ignore_ascii_case(start) && r.eq_ignore_ascii_case(end))
            || (r.eq_ignore_ascii_case(start) && l.eq_ignore_ascii_case(end))
    })
}

fn factor_adjacent(branches: Vec<Pattern>, disjoint: &[(String, String)]) -> Pattern {
    let mut result: Vec<Pattern> = Vec::with_capacity(branches.len());
    for branch in branches {
        let common = result.last().map_or(0, |previous| {
            let (left, right) = (parts(previous), parts(&branch));
            let mut common = 0;
            while common < left.len().min(right.len()) {
                if same_fixed_part(&left[common], &right[common]) {
                    common += 1;
                } else if shared_delimited_word(
                    &left[common..],
                    &right[common..],
                    disjoint,
                ) {
                    common += 2;
                } else {
                    break;
                }
            }
            common
        });
        let partial = result.last().and_then(|previous| {
            parts(previous)
                .get(common)
                .zip(parts(&branch).get(common))
                .and_then(|(left, right)| share_mandatory_word(left, right))
        });
        if common == 0 && partial.is_none() {
            result.push(branch);
            continue;
        }
        let previous = result.pop().expect("a shared preceding branch");
        let mut prefix = into_parts(previous);
        let mut tail = prefix.split_off(common);
        let mut suffix = into_parts(branch)
            .into_iter()
            .skip(common)
            .collect::<Vec<_>>();
        if let Some((shared, left, right)) = partial {
            prefix.push(shared);
            if let Some(left) = left {
                tail[0] = left;
            } else {
                tail.remove(0);
            }
            if let Some(right) = right {
                suffix[0] = right;
            } else {
                suffix.remove(0);
            }
            // Stop here: optional lengths must stay behind the original branch
            // choice, including when both remaining repetitions look identical.
        }
        let tail = concat(tail);
        let suffix = concat(suffix);
        // Only adjacent alternatives move together. An empty suffix stays at
        // its original position, preserving shorter-first and longer-first
        // choices. Unresolved lengths and excluded rows stay in the branches.
        let mut choices = match tail {
            Pattern::Alternation(choices) => choices,
            other => vec![other],
        };
        choices.push(suffix);
        prefix.push(Pattern::Alternation(choices));
        result.push(concat(prefix));
    }
    if result.len() == 1 {
        result.pop().expect("one factored branch")
    } else {
        Pattern::Alternation(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::test_support::all_matches;

    fn factor(pattern: Pattern) -> Pattern {
        super::factor(pattern, &[])
    }

    fn symbol(name: &str) -> Pattern {
        Pattern::Symbol(Symbol::Named(name.into()))
    }

    fn word(names: &[&str]) -> Pattern {
        concat(names.iter().map(|name| symbol(name)).collect())
    }

    fn alt(branches: Vec<Pattern>) -> Pattern {
        Pattern::Alternation(branches)
    }

    fn repeat(pattern: Pattern, quantifier: RepetitionQuantifier) -> Pattern {
        Pattern::Repetition(Box::new(pattern), quantifier)
    }

    fn assert_same_matches(before: &Pattern, after: &Pattern, signatures: &[&str]) {
        for length in 0..=3 {
            for mut assignment in 0..signatures.len().pow(length) {
                let rows = (0..length)
                    .map(|_| {
                        let row = signatures[assignment % signatures.len()];
                        assignment /= signatures.len();
                        row
                    })
                    .collect::<Vec<_>>();
                assert_eq!(
                    all_matches(before, &rows),
                    all_matches(after, &rows),
                    "{before} -> {after}, rows={rows:?}"
                );
            }
        }
    }

    #[test]
    fn delimited_repeats_preserve_classifiers_and_ordered_empty_suffixes() {
        use RepetitionQuantifier::{
            OneOrMoreReluctant, Range, RangeReluctant, ZeroOrMore,
        };
        let disjoint = [("b".into(), "x".into())];
        let signatures = ["", "X", "B", "C", "XC", "BC"];
        for body in [symbol("X"), word(&["X", "C"])] {
            for quantifier in [
                ZeroOrMore,
                OneOrMoreReluctant,
                Range(0, 2),
                RangeReluctant(1, 3),
            ] {
                let repeated = repeat(body.clone(), quantifier);
                for (left, right) in [(symbol("C"), word(&[])), (word(&[]), symbol("C"))]
                {
                    let arm = |tail| concat(vec![repeated.clone(), symbol("B"), tail]);
                    let before = alt(vec![arm(left.clone()), arm(right.clone())]);
                    let expected = concat(vec![
                        repeated.clone(),
                        symbol("B"),
                        alt(vec![left, right]),
                    ]);
                    let after = super::factor(before.clone(), &disjoint);
                    assert_eq!(after, expected);
                    assert_same_matches(&before, &after, &signatures);
                    let rows = ["XC", "C", "X", "BC", "C", "C"];
                    assert_eq!(all_matches(&before, &rows), all_matches(&after, &rows));
                }
            }
        }
    }

    #[test]
    fn overlapping_delimiter_keeps_the_branch_choice_before_the_split_choice() {
        let star = repeat(symbol("X"), RepetitionQuantifier::ZeroOrMore);
        let original = alt(vec![
            concat(vec![star.clone(), symbol("B"), symbol("C")]),
            concat(vec![star.clone(), symbol("B")]),
        ]);
        let invalid = concat(vec![star, symbol("B"), alt(vec![symbol("C"), word(&[])])]);
        let unrelated = [("X".into(), "C".into())];
        assert_eq!(super::factor(original.clone(), &unrelated), original);
        let rows = ["XB", "BC"];
        let labels = |p| {
            all_matches(p, &rows)
                .into_iter()
                .map(|r| r.classifier.unwrap())
                .collect::<Vec<_>>()
        };
        assert_eq!(labels(&original), ["B", "C"]);
        assert_eq!(labels(&invalid), ["X", "B"]);
    }

    #[test]
    fn exact_repetitions_share_without_expansion_or_internal_choices() {
        use RepetitionQuantifier::{Exactly, ExactlyReluctant, OneOrMore};
        for body in [symbol("A"), word(&["A", "B"])] {
            let prefix = repeat(body.clone(), Exactly(3));
            let reluctant = repeat(body, ExactlyReluctant(3));
            for (before, tails) in [
                (
                    alt(vec![
                        concat(vec![prefix.clone(), symbol("C")]),
                        reluctant.clone(),
                    ]),
                    vec![symbol("C"), word(&[])],
                ),
                (
                    alt(vec![prefix.clone(), concat(vec![reluctant, symbol("C")])]),
                    vec![word(&[]), symbol("C")],
                ),
            ] {
                assert_eq!(factor(before), concat(vec![prefix.clone(), alt(tails)]));
            }
        }
        for body in [
            repeat(symbol("A"), OneOrMore),
            alt(vec![symbol("A"), symbol("B")]),
            Pattern::Exclude(Symbol::Named("A".into())),
            concat(vec![symbol("A"), Pattern::Symbol(Symbol::Start)]),
            word(&[]),
        ] {
            let prefix = repeat(body, Exactly(2));
            let pattern = alt(vec![concat(vec![prefix.clone(), symbol("C")]), prefix]);
            assert_eq!(factor(pattern.clone()), pattern);
        }
        assert!(!same_fixed_part(
            &repeat(symbol("A"), Exactly(2)),
            &repeat(symbol("A"), Exactly(3)),
        ));
    }

    #[test]
    fn mandatory_copies_leave_each_branches_length_choices_in_place() {
        use RepetitionQuantifier::{
            Exactly, OneOrMore, Range, RangeReluctant, ZeroOrMore,
        };
        let a = symbol("A");
        for (left, right, shared, left_tail, right_tail) in [
            (
                repeat(a.clone(), Exactly(5)),
                repeat(a.clone(), Exactly(2)),
                repeat(a.clone(), Exactly(2)),
                concat(vec![repeat(a.clone(), Exactly(3)), symbol("B")]),
                symbol("C"),
            ),
            (
                repeat(a.clone(), OneOrMore),
                repeat(a.clone(), OneOrMore),
                a.clone(),
                concat(vec![repeat(a.clone(), ZeroOrMore), symbol("B")]),
                concat(vec![repeat(a.clone(), ZeroOrMore), symbol("C")]),
            ),
            (
                repeat(a.clone(), Range(2, 4)),
                repeat(a.clone(), RangeReluctant(1, 3)),
                a.clone(),
                concat(vec![repeat(a.clone(), Range(1, 3)), symbol("B")]),
                concat(vec![repeat(a.clone(), RangeReluctant(0, 2)), symbol("C")]),
            ),
        ] {
            let before = alt(vec![
                concat(vec![left, symbol("B")]),
                concat(vec![right, symbol("C")]),
            ]);
            assert_eq!(
                factor(before),
                concat(vec![shared, alt(vec![left_tail, right_tail])])
            );
        }
        let prefix = repeat(a, Exactly(2));
        let original = alt(vec![
            concat(vec![prefix.clone(), symbol("B")]),
            concat(vec![repeat(symbol("A"), Exactly(5)), symbol("B")]),
        ]);
        assert_eq!(
            factor(original),
            concat(vec![
                prefix,
                alt(vec![
                    symbol("B"),
                    concat(vec![repeat(symbol("A"), Exactly(3)), symbol("B")])
                ])
            ])
        );
    }

    #[test]
    fn adjacent_fixed_prefixes_preserve_branch_order_and_empty_suffixes() {
        let a = symbol("A");
        for (before, after) in [
            (
                alt(vec![word(&["A", "B"]), a.clone()]),
                concat(vec![a.clone(), alt(vec![symbol("B"), word(&[])])]),
            ),
            (
                alt(vec![a.clone(), word(&["A", "B"])]),
                concat(vec![a.clone(), alt(vec![word(&[]), symbol("B")])]),
            ),
            (
                alt(vec![word(&["A", "B", "C"]), word(&["A", "B", "D"])]),
                concat(vec![
                    a.clone(),
                    symbol("B"),
                    alt(vec![symbol("C"), symbol("D")]),
                ]),
            ),
            (
                alt(vec![
                    word(&["A", "B"]),
                    word(&["A", "C"]),
                    word(&["A", "D"]),
                ]),
                concat(vec![a, alt(vec![symbol("B"), symbol("C"), symbol("D")])]),
            ),
        ] {
            assert_eq!(factor(before), after);
        }
        let star =
            Pattern::Repetition(Box::new(symbol("A")), RepetitionQuantifier::ZeroOrMore);
        let excluded = Pattern::Exclude(Symbol::Named("A".into()));
        for pattern in [
            alt(vec![word(&["A", "B"]), symbol("X"), word(&["A", "C"])]),
            alt(vec![
                concat(vec![star.clone(), symbol("B")]),
                concat(vec![star, symbol("C")]),
            ]),
            alt(vec![
                concat(vec![excluded.clone(), symbol("B")]),
                concat(vec![excluded, symbol("C")]),
            ]),
        ] {
            assert_eq!(factor(pattern.clone()), pattern);
        }
    }

    #[test]
    fn fixed_prefix_factoring_preserves_reference_classifiers_and_preference() {
        use RepetitionQuantifier::{
            Exactly, ExactlyReluctant, OneOrMore, Range, RangeReluctant,
        };
        let fixed = repeat(symbol("A"), Exactly(2));
        let patterns = [
            alt(vec![word(&["A", "B"]), symbol("A")]),
            alt(vec![symbol("A"), word(&["A", "B"])]),
            alt(vec![
                word(&["A", "B"]),
                word(&["A", "C"]),
                word(&["A", "B", "C"]),
            ]),
            alt(vec![word(&["A", "B"]), symbol("C"), word(&["A", "C"])]),
            concat(vec![alt(vec![word(&["A", "B"]), symbol("A")]), symbol("C")]),
            Pattern::Repetition(
                Box::new(alt(vec![word(&["A", "B"]), symbol("A")])),
                OneOrMore,
            ),
            Pattern::Repetition(
                Box::new(alt(vec![symbol("A"), word(&["A", "B"])])),
                RepetitionQuantifier::OneOrMoreReluctant,
            ),
            alt(vec![
                concat(vec![fixed.clone(), symbol("B")]),
                concat(vec![repeat(symbol("A"), ExactlyReluctant(2)), symbol("C")]),
            ]),
            alt(vec![
                concat(vec![fixed.clone(), symbol("B")]),
                fixed.clone(),
            ]),
            alt(vec![fixed.clone(), concat(vec![fixed, symbol("B")])]),
            alt(vec![
                concat(vec![repeat(symbol("A"), Exactly(3)), symbol("B")]),
                concat(vec![repeat(symbol("A"), Exactly(2)), symbol("C")]),
            ]),
            alt(vec![
                concat(vec![repeat(symbol("A"), Exactly(2)), symbol("B")]),
                concat(vec![repeat(symbol("A"), Exactly(3)), symbol("C")]),
            ]),
            alt(vec![
                concat(vec![repeat(symbol("A"), OneOrMore), symbol("B")]),
                concat(vec![repeat(symbol("A"), OneOrMore), symbol("C")]),
            ]),
            alt(vec![
                concat(vec![repeat(symbol("A"), Range(2, 4)), symbol("B")]),
                concat(vec![repeat(symbol("A"), RangeReluctant(1, 3)), symbol("C")]),
            ]),
            concat(vec![
                repeat(
                    alt(vec![
                        concat(vec![repeat(symbol("A"), OneOrMore), symbol("B")]),
                        concat(vec![repeat(symbol("A"), Exactly(2)), symbol("C")]),
                    ]),
                    RepetitionQuantifier::OneOrMoreReluctant,
                ),
                symbol("C"),
            ]),
        ];
        for pattern in patterns {
            let factored = factor(pattern.clone());
            for rows in [
                vec!["A", "A", "A", "A", "A", "B", "A", "A", "C"],
                vec!["AB", "AB", "ABC", "A", "AC", "C"],
                vec!["A", "A", "B", "A", "A", "C", "C"],
            ] {
                assert_eq!(
                    all_matches(&factored, &rows),
                    all_matches(&pattern, &rows),
                    "{pattern} -> {factored}, rows={rows:?}"
                );
            }
            assert_same_matches(
                &pattern,
                &factored,
                &["", "A", "B", "C", "AB", "AC", "BC", "ABC"],
            );
        }
        let fixed = repeat(word(&["A", "B"]), Exactly(2));
        for pattern in [
            alt(vec![
                concat(vec![fixed.clone(), symbol("C")]),
                fixed.clone(),
            ]),
            alt(vec![fixed.clone(), concat(vec![fixed, symbol("C")])]),
            alt(vec![
                concat(vec![repeat(word(&["A", "B"]), Exactly(3)), symbol("C")]),
                concat(vec![repeat(word(&["A", "B"]), Exactly(2)), symbol("C")]),
            ]),
        ] {
            let factored = factor(pattern.clone());
            for rows in [
                vec!["A", "B", "A", "B", "A", "B", "C"],
                vec!["A", "B", "A", "B", "C", "A", "B", "A", "B"],
                vec!["AB", "AB", "AB", "AB", "BC"],
                vec!["A", "B", "", "A", "B", "A", "B", "C"],
            ] {
                assert_eq!(all_matches(&factored, &rows), all_matches(&pattern, &rows));
            }
        }
    }
}