datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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
// 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.

//! A sufficient static proof that successful matches cannot overlap.

use std::collections::{HashMap, HashSet};

use crate::nfa::{AutomatonStateId, CompiledAutomaton};
use crate::planning::SymbolRelationships;
use datafusion_common::{DataFusionError, Result};

use super::fallible_vec::{filled, reserved};

const FIRST: u8 = 1;
const TAIL: u8 = 2;
const MAX_PRODUCT_PAIRS: usize = 4_096;
const MAX_PRODUCT_WORK: usize = 100_000;

type StatePair = (AutomatonStateId, AutomatonStateId);

/// Planning may decline this optional proof before exploring a large product.
struct OverlapProduct {
    pending: Vec<StatePair>,
    seen: HashSet<StatePair>,
    pair_limit: usize,
    remaining_work: usize,
}

impl OverlapProduct {
    fn new(state_count: usize, pair_limit: usize, work_limit: usize) -> Result<Self> {
        let capacity = state_count.saturating_mul(state_count).min(pair_limit);
        let mut seen = HashSet::new();
        seen.try_reserve(capacity).map_err(|error| {
            DataFusionError::ResourcesExhausted(format!(
                "MATCH_RECOGNIZE non-overlap product allocation failed: {error}"
            ))
        })?;
        Ok(Self {
            pending: reserved(capacity, "non-overlap product entries")?,
            seen,
            pair_limit,
            remaining_work: work_limit,
        })
    }

    fn visit(&mut self, pair: StatePair) -> bool {
        if self.seen.contains(&pair) {
            return true;
        }
        if self.seen.len() == self.pair_limit {
            return false;
        }
        self.seen.insert(pair);
        self.pending.push(pair);
        true
    }

    fn step(&mut self) -> bool {
        let Some(remaining) = self.remaining_work.checked_sub(1) else {
            return false;
        };
        self.remaining_work = remaining;
        true
    }

    /// Consume the same input row on both paths. Unknown symbol relationships
    /// are compatible; only a proven disjoint pair rules out a shared row.
    fn advance(
        &mut self,
        automaton: &CompiledAutomaton,
        disjoint: &HashSet<(usize, usize)>,
        pair: StatePair,
    ) -> bool {
        let nfa = automaton.nfa();
        // Anchors are the only conditional epsilon edges, and admission
        // excludes them. Cached dispatch therefore covers every epsilon path;
        // ignoring possessive suppression still overapproximates the language.
        for &left_source in nfa.state(pair.0).unconditional_dispatch() {
            if !self.step() {
                return false;
            }
            for (left_symbol, left_targets) in nfa.state(left_source).transition_rows() {
                if !self.step() {
                    return false;
                }
                if left_targets.is_empty() {
                    continue;
                }
                for &right_source in nfa.state(pair.1).unconditional_dispatch() {
                    if !self.step() {
                        return false;
                    }
                    for (right_symbol, right_targets) in
                        nfa.state(right_source).transition_rows()
                    {
                        if !self.step() {
                            return false;
                        }
                        let left = left_symbol.index();
                        let right = right_symbol.index();
                        if right_targets.is_empty()
                            || disjoint.contains(&(left.min(right), left.max(right)))
                        {
                            continue;
                        }
                        for &left_target in left_targets {
                            for &right_target in right_targets {
                                if !self.step()
                                    || !self.visit((left_target, right_target))
                                {
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
        }
        true
    }
}

fn visit(
    state: AutomatonStateId,
    phase: u8,
    seen: &mut [u8],
    pending: &mut Vec<(AutomatonStateId, u8)>,
) {
    if seen[state.index()] & phase == 0 {
        seen[state.index()] |= phase;
        pending.push((state, phase));
    }
}

/// Prove that no successful match can begin inside another successful match,
/// so PAST LAST ROW suppresses no successful start.
///
/// The caller must establish static, row-local membership. Finite span, output
/// locality and other Halo requirements remain separate admission checks.
/// False means unknown, including when the bounded product cannot finish.
pub(crate) fn proves_non_overlapping_starts(
    automaton: &CompiledAutomaton,
    relationships: &SymbolRelationships,
) -> Result<bool> {
    if automaton.has_anchors() || automaton.min_match_rows() == 0 {
        return Ok(false);
    }
    let states = automaton.nfa().state_count();
    let capacity = states.checked_mul(2).ok_or_else(|| {
        DataFusionError::ResourcesExhausted("non-overlap traversal exceeds usize".into())
    })?;
    let mut seen = filled(states, 0u8, "non-overlap state marks")?;
    let mut symbols = filled(automaton.num_symbols(), 0u8, "non-overlap symbol marks")?;
    let mut pending = reserved(capacity, "non-overlap traversal entries")?;
    visit(
        automaton.nfa().start_state(),
        FIRST,
        &mut seen,
        &mut pending,
    );
    while let Some((state, phase)) = pending.pop() {
        let state = automaton.nfa().state(state);
        // Taking every epsilon edge and ignoring possessive suppression
        // overapproximates possible histories; it can only lose a proof.
        for edge in state.epsilon_transitions() {
            visit(edge.target(), phase, &mut seen, &mut pending);
        }
        // Dense named transition rows cover the complete symbol domain,
        // including symbols beyond the first 64 bitmap positions.
        for (symbol, targets) in state.transition_rows() {
            if !targets.is_empty() {
                symbols[symbol.index()] |= phase;
            }
            for &target in targets {
                visit(target, TAIL, &mut seen, &mut pending);
            }
        }
    }
    let mut first = 0usize;
    let mut tail = 0usize;
    let mut distinct = true;
    for &phase in &symbols {
        first += usize::from(phase & FIRST != 0);
        tail += usize::from(phase & TAIL != 0);
        distinct &= phase != (FIRST | TAIL);
    }
    if first == 0 {
        return Ok(false);
    }
    let Some(required) = first.checked_mul(tail) else {
        return Ok(false);
    };
    if required == 0 {
        return Ok(true);
    }
    if relationships.disjoint.is_empty() {
        return Ok(false);
    }
    let allocation_error = |error| {
        DataFusionError::ResourcesExhausted(format!(
            "MATCH_RECOGNIZE non-overlap facts allocation failed: {error}"
        ))
    };
    // Checked logical relationships use canonical symbol names. Borrow them
    // from this exact automaton; unknown names cannot supply a proof.
    let mut ids = HashMap::new();
    ids.try_reserve(automaton.num_symbols())
        .map_err(allocation_error)?;
    for (symbol, name) in automaton.symbols_iter() {
        ids.insert(name, symbol.index());
    }
    let mut disjoint = HashSet::new();
    disjoint
        .try_reserve(relationships.disjoint.len())
        .map_err(allocation_error)?;
    let mut separated = 0usize;
    for (left, right) in &relationships.disjoint {
        if let (Some(&left), Some(&right)) =
            (ids.get(left.as_str()), ids.get(right.as_str()))
            && disjoint.insert((left.min(right), left.max(right)))
            && ((symbols[left] == FIRST && symbols[right] == TAIL)
                || (symbols[left] == TAIL && symbols[right] == FIRST))
        {
            separated += 1;
        }
    }
    // This cheap separator proves larger graphs without building a product.
    if distinct && separated == required {
        return Ok(true);
    }

    let mut product = OverlapProduct::new(states, MAX_PRODUCT_PAIRS, MAX_PRODUCT_WORK)?;
    let start = automaton.nfa().start_state();
    for (index, phase) in seen.into_iter().enumerate() {
        if phase & TAIL != 0 {
            // The earlier path has consumed >=1 row. Seed only after a shared
            // consuming step: accepting at this boundary alone would confuse
            // a new match after the earlier end with an overlapping start.
            let earlier = automaton.nfa().state_id(index).unwrap();
            if !product.advance(automaton, &disjoint, (earlier, start)) {
                return Ok(false);
            }
        }
        if !product.step() {
            return Ok(false);
        }
    }
    let accepting = automaton.unconditional_first_accepting_state();
    while let Some(pair) = product.pending.pop() {
        // The two matches need not end together. Refuse the proof when either
        // can finish, even if the other has not yet proved an accepting suffix.
        // This overapproximation avoids extra suffix/latch state and is safe
        // for dead branches as well as greedy, reluctant and possessive paths.
        if accepting[pair.0.index()].is_some() || accepting[pair.1.index()].is_some() {
            return Ok(false);
        }
        if !product.advance(automaton, &disjoint, pair) {
            return Ok(false);
        }
        if !product.step() {
            return Ok(false);
        }
    }
    Ok(true)
}

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

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

    fn sequence(names: &[&str]) -> Pattern {
        Pattern::Concat(names.iter().map(|name| named(name)).collect())
    }

    fn repeat(name: &str, quantifier: RepetitionQuantifier) -> Pattern {
        Pattern::Repetition(Box::new(named(name)), quantifier)
    }

    fn prove(
        pattern: Pattern,
        pairs: &[(&str, &str)],
        names: Option<Vec<String>>,
    ) -> bool {
        let names = names.unwrap_or_else(|| pattern.symbol_names().into_iter().collect());
        let compiled =
            CompiledAutomaton::compile(&NormalizedPattern::Ast(pattern), &names).unwrap();
        let relationships = SymbolRelationships {
            disjoint: pairs
                .iter()
                .map(|(a, b)| (a.to_string(), b.to_string()))
                .collect(),
            ..Default::default()
        };
        proves_non_overlapping_starts(&compiled, &relationships).unwrap()
    }

    #[test]
    fn fixed_words_agree_with_the_prefix_suffix_overlap_rule() {
        for length in 1..=5 {
            for bits in 0..(1 << length) {
                let word = (0..length)
                    .map(|index| if bits & (1 << index) == 0 { "A" } else { "B" })
                    .collect::<Vec<_>>();
                let non_overlapping =
                    (1..length).all(|prefix| word[..prefix] != word[length - prefix..]);
                assert_eq!(
                    prove(sequence(&word), &[("A", "B")], None),
                    non_overlapping,
                    "{word:?}"
                );
            }
        }
    }

    #[test]
    fn non_overlap_checks_shared_rows_and_keeps_unknown_cases_conservative() {
        let first_alternatives = Pattern::Concat(vec![
            Pattern::Alternation(vec![named("A"), named("B")]),
            named("C"),
        ]);
        type Case<'a> = (Pattern, &'a [(&'a str, &'a str)], bool);
        let cases: Vec<Case<'_>> = vec![
            (
                sequence(&["A", "A", "B", "C"]),
                &[("A", "B"), ("A", "C")],
                true,
            ),
            (
                Pattern::Concat(vec![
                    named("A"),
                    named("A"),
                    Pattern::Alternation(vec![named("B"), named("C")]),
                    named("D"),
                ]),
                &[("A", "B"), ("A", "C"), ("A", "D")],
                true,
            ),
            (sequence(&["A", "B"]), &[("A", "B")], true),
            (sequence(&["A", "B"]), &[], false),
            (sequence(&["A", "B"]), &[("A", "UNKNOWN")], false),
            (sequence(&["Start", "Finish"]), &[("Start", "Finish")], true),
            (
                sequence(&["Start", "Finish"]),
                &[("start", "FINISH")],
                false,
            ),
            (
                Pattern::Concat(vec![
                    named("A"),
                    repeat("B", RepetitionQuantifier::Range(1, 3)),
                ]),
                &[("B", "A")],
                true,
            ),
            (
                Pattern::Concat(vec![
                    named("A"),
                    Pattern::Alternation(vec![named("B"), named("C")]),
                ]),
                &[("A", "B"), ("A", "C")],
                true,
            ),
            (first_alternatives.clone(), &[("A", "C"), ("B", "C")], true),
            // Duplicate/reversed facts must not stand in for the missing B/C fact.
            (first_alternatives, &[("A", "C"), ("C", "A")], false),
            (
                Pattern::Concat(vec![
                    named("A"),
                    Pattern::Exclude(Symbol::Named("B".into())),
                    named("C"),
                ]),
                &[("A", "B"), ("A", "C")],
                true,
            ),
            (
                Pattern::Concat(vec![
                    named("A"),
                    repeat("B", RepetitionQuantifier::AtMostOne),
                ]),
                &[("A", "B")],
                true,
            ),
            (
                Pattern::Concat(vec![
                    repeat("A", RepetitionQuantifier::AtMostOne),
                    named("B"),
                ]),
                &[("A", "B")],
                false,
            ),
            (
                Pattern::Concat(vec![
                    repeat("A", RepetitionQuantifier::Range(1, 2)),
                    named("B"),
                ]),
                &[("A", "B")],
                false,
            ),
            // The shared suffix A B conflicts with the later prefix A A.
            (sequence(&["A", "A", "B"]), &[("A", "B")], true),
            (sequence(&["A", "A", "B", "B"]), &[("A", "B")], true),
            (sequence(&["A", "B", "A"]), &[("A", "B")], false),
            (sequence(&["A", "B", "A", "B"]), &[("A", "B")], false),
            (sequence(&["A", "A", "B", "A", "B"]), &[("A", "B")], true),
            (
                Pattern::Concat(vec![
                    sequence(&["A", "A", "B", "A"]),
                    repeat("B", RepetitionQuantifier::AtMostOne),
                ]),
                &[("A", "B")],
                false,
            ),
            // Later B finishes inside the earlier A B C match.
            (
                Pattern::Alternation(vec![sequence(&["A", "B", "C"]), named("B")]),
                &[("A", "B"), ("A", "C"), ("B", "C")],
                false,
            ),
            (
                Pattern::Alternation(vec![
                    Pattern::Concat(vec![
                        named("A"),
                        Pattern::Exclude(Symbol::Named("B".into())),
                        named("C"),
                    ]),
                    named("B"),
                ]),
                &[("A", "B"), ("A", "C"), ("B", "C")],
                false,
            ),
            // Later B C D finishes after the earlier A B match.
            (
                Pattern::Alternation(vec![
                    sequence(&["A", "B"]),
                    sequence(&["B", "C", "D"]),
                ]),
                &[
                    ("A", "B"),
                    ("A", "C"),
                    ("A", "D"),
                    ("B", "C"),
                    ("B", "D"),
                    ("C", "D"),
                ],
                false,
            ),
            (
                Pattern::Permute(vec![
                    Symbol::Named("A".into()),
                    Symbol::Named("B".into()),
                ]),
                &[("A", "B")],
                false,
            ),
            (repeat("A", RepetitionQuantifier::AtMostOne), &[], false),
            (
                Pattern::Concat(vec![
                    Pattern::Symbol(Symbol::Start),
                    named("A"),
                    named("B"),
                ]),
                &[("A", "B")],
                false,
            ),
            // Non-overlap and finite span are independent: Halo still rejects B+.
            (
                Pattern::Concat(vec![
                    named("A"),
                    repeat("B", RepetitionQuantifier::OneOrMore),
                ]),
                &[("A", "B")],
                true,
            ),
        ];
        for (pattern, facts, expected) in cases {
            assert_eq!(
                prove(pattern.clone(), facts, None),
                expected,
                "{pattern:?}, {facts:?}"
            );
        }
    }

    #[test]
    fn non_overlap_uses_high_symbol_ids_and_retains_the_pruned_symbol_domain() {
        let names = (0..70).map(|i| format!("S{i}")).collect::<Vec<_>>();
        for (pattern, pairs, expected) in [
            (sequence(&["S0", "S69"]), vec![("S0", "S69")], true),
            // Ignoring the high-ID tail would incorrectly make the proof vacuous.
            (sequence(&["S0", "S69"]), vec![], false),
            (sequence(&["S69", "S0", "S69"]), vec![("S69", "S0")], false),
            (sequence(&["S69", "S69", "S0"]), vec![("S69", "S0")], true),
        ] {
            assert_eq!(prove(pattern, &pairs, Some(names.clone())), expected);
        }
    }

    #[test]
    fn non_overlap_fixed_runs_are_proven_but_variable_runs_can_overlap() {
        for length in [2, 3, 5, 8] {
            assert!(prove(
                Pattern::Concat(vec![
                    repeat("A", RepetitionQuantifier::Range(length, length)),
                    named("B"),
                ]),
                &[("A", "B")],
                None,
            ));
        }
        assert!(!prove(
            Pattern::Concat(vec![
                repeat("A", RepetitionQuantifier::Range(2, 3)),
                named("B"),
            ]),
            &[("A", "B")],
            None,
        ));
        assert!(!prove(
            Pattern::Alternation(vec![sequence(&["A", "B"]), named("B")]),
            &[("A", "B")],
            None,
        ));
    }

    #[test]
    fn non_overlap_product_declines_when_its_optional_budget_is_exhausted() {
        let compiled = CompiledAutomaton::compile(
            &NormalizedPattern::Ast(sequence(&["A", "A", "B"])),
            &["A".into(), "B".into()],
        )
        .unwrap();
        let start = compiled.nfa().start_state();
        let other = compiled
            .nfa()
            .state_id((start.index() + 1) % compiled.nfa().state_count())
            .unwrap();
        let mut product =
            OverlapProduct::new(compiled.nfa().state_count(), 1, 0).unwrap();
        assert!(product.visit((start, start)));
        assert!(product.visit((start, start)));
        assert!(!product.visit((start, other)));
        assert!(!product.advance(&compiled, &HashSet::new(), (start, start)));
    }
}