datafusion-match-recognize 0.56.1

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
// 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.

//! Pattern normalization from structural and caller-provided semantic facts.
//!
//! [`PatternOptimizer`] removes structural identities and impossible anchors,
//! simplifies quantifiers, and can use complete-scope symbol status to prune
//! impossible branches. Disjointness and implication facts enable additional
//! rewrites only where they preserve match selection and preference, including
//! safe possessive promotion.
//!
//! Each [`PatternOptimizer::optimize`] call is independent. It memoizes facts
//! only for its immutable normalized root and computes temporary nodes fresh.
//! It returns a public [`NormalizedPattern`] outcome;
//! mutable compiler state is not retained between calls.

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

use crate::core::{NormalizedPattern, Pattern, PatternStructuralInfo, Symbol};

use crate::nfa::pattern_optimizer::symbol_runs::{
    normalize_symbol_and_anchor_runs, normalize_symbol_runs,
};
use crate::nfa::pattern_optimizer::types::{RowsConsumed, SymbolStatus};

/// Normalize a pattern using structural facts and optional symbol evidence.
///
/// Enabling status-based pruning requires evidence for the complete represented
/// input scope. Disjointness and implication relationships have their more
/// specific contracts on the corresponding builder methods.
///
/// # Example
///
/// ```text
/// use std::collections::HashMap;
/// use crate::core::{NormalizedPattern, Pattern, Symbol};
/// use crate::nfa::{PatternOptimizer, SymbolStatus};
///
/// let mut status = HashMap::new();
/// status.insert("B".to_string(), SymbolStatus::False);
///
/// let optimizer = PatternOptimizer::new(&status).with_allow_pruning(true);
/// let pattern = Pattern::Symbol(Symbol::Named("B".to_string()));
/// let result = optimizer.optimize(&pattern);
/// assert!(matches!(result, NormalizedPattern::Never));
/// ```
pub struct PatternOptimizer<'a> {
    pub(crate) symbol_status: &'a HashMap<String, SymbolStatus>,
    pub(crate) normalized_symbol_status: HashMap<String, SymbolStatus>,
    /// Set of symbol pairs that are known to be mutually exclusive.
    pub(crate) normalized_disjoint_pairs: Option<HashSet<(String, String)>>,
    /// Set of symbol pairs (A, B) where A implies B (A is a subset of B).
    pub(crate) normalized_implies_pairs: Option<HashSet<(String, String)>>,
    /// Whether to allow pruning parts of the pattern that are known to never match.
    /// Should only be true if symbol_status represents the entire partition.
    pub(crate) allow_pruning: bool,
    /// Shared memoized facts owned by one optimization session.
    pub(crate) pattern_facts: PatternFacts,
}

/// Structural facts derived from a pattern.
#[derive(Debug, Clone)]
pub(crate) struct PatternFact {
    pub(crate) leading_symbols: Vec<String>,
    pub(crate) structural_info: PatternStructuralInfo,
    // Every viable path tests these anchors. Unlike output-position flags,
    // these constraints also apply to excluded anchors and required repeats.
    pub(crate) mandatory_start_anchor: bool,
    pub(crate) mandatory_end_anchor: bool,
    pub(crate) impossible_anchor: Option<String>,
}

#[derive(Default)]
pub(crate) struct PatternFacts {
    /// Only live nodes of the immutable optimization root may enter this map.
    /// Integer addresses preserve the optimizer's existing `Send` behavior.
    pub(crate) cache: RefCell<HashMap<usize, PatternFact>>,
}

impl PatternFacts {
    pub(crate) fn clear(&self) {
        self.cache.borrow_mut().clear();
    }

    /// Index `root` before optimization. It must stay alive, unmoved and
    /// unchanged until `clear()`, so no temporary can occupy a cached address.
    pub(crate) fn index_root(&self, root: &Pattern) {
        self.clear();
        self.index_node(root);
    }

    fn index_node(&self, pattern: &Pattern) {
        match pattern {
            Pattern::Concat(children) | Pattern::Alternation(children) => {
                children.iter().for_each(|child| self.index_node(child));
            }
            Pattern::Group(inner) | Pattern::Repetition(inner, _) => {
                self.index_node(inner);
            }
            Pattern::Symbol(_) | Pattern::Exclude(_) | Pattern::Permute(_) => {}
        }
        let fact = self.compute_fact(pattern);
        self.cache
            .borrow_mut()
            .insert(std::ptr::from_ref(pattern) as usize, fact);
    }

    /// Reuse root facts; compute every other node without retaining its address.
    pub(crate) fn fact(&self, pattern: &Pattern) -> PatternFact {
        let key = std::ptr::from_ref(pattern) as usize;
        if let Some(cached) = self.cache.borrow().get(&key) {
            return cached.clone();
        }
        self.compute_fact(pattern)
    }

    fn child_facts<'a>(
        &self,
        patterns: impl IntoIterator<Item = &'a Pattern>,
    ) -> Vec<PatternFact> {
        patterns
            .into_iter()
            .map(|pattern| self.fact(pattern))
            .collect()
    }

    fn collect_leading_symbols(
        child_facts: &[PatternFact],
        stop_after_required_child: bool,
    ) -> Vec<String> {
        let mut leading_symbols = Vec::new();
        for fact in child_facts {
            leading_symbols.extend(fact.leading_symbols.iter().cloned());
            if stop_after_required_child && !fact.structural_info.can_match_empty() {
                break;
            }
        }
        leading_symbols
    }

    fn impossible_alternation_reason(child_facts: &[PatternFact]) -> Option<String> {
        let (first, rest) = child_facts.split_first()?;
        let reason = first.impossible_anchor.as_ref()?;
        rest.iter()
            .all(|fact| fact.impossible_anchor.is_some())
            .then(|| reason.clone())
    }

    fn compute_fact(&self, pattern: &Pattern) -> PatternFact {
        match pattern {
            Pattern::Symbol(symbol) | Pattern::Exclude(symbol) => PatternFact {
                leading_symbols: match symbol {
                    Symbol::Named(name) => vec![name.clone()],
                    Symbol::Start | Symbol::End => Vec::new(),
                },
                structural_info: pattern.structural_info(),
                mandatory_start_anchor: matches!(symbol, Symbol::Start),
                mandatory_end_anchor: matches!(symbol, Symbol::End),
                impossible_anchor: None,
            },
            Pattern::Permute(symbols) => PatternFact {
                leading_symbols: symbols
                    .iter()
                    .filter_map(|symbol| match symbol {
                        Symbol::Named(name) => Some(name.clone()),
                        Symbol::Start | Symbol::End => None,
                    })
                    .collect(),
                structural_info: PatternStructuralInfo::for_permute(symbols),
                mandatory_start_anchor: symbols.contains(&Symbol::Start),
                mandatory_end_anchor: symbols.contains(&Symbol::End),
                impossible_anchor: None,
            },
            Pattern::Concat(parts) => self.compute_concat_fact(parts),
            Pattern::Group(inner) => self.fact(inner),
            Pattern::Alternation(patterns) => {
                let child_facts = self.child_facts(patterns.iter());
                let child_info = child_facts
                    .iter()
                    .map(|fact| fact.structural_info)
                    .collect::<Vec<_>>();
                let leading_symbols = Self::collect_leading_symbols(&child_facts, false);
                let impossible_anchor = Self::impossible_alternation_reason(&child_facts);
                // An impossible arm cannot provide an anchor-free bypass.
                // Keep the empty set non-mandatory rather than relying on a
                // vacuous all() result for an already impossible alternation.
                let mut viable = child_facts
                    .iter()
                    .filter(|fact| fact.impossible_anchor.is_none())
                    .peekable();
                let has_viable = viable.peek().is_some();
                let mandatory_start_anchor =
                    has_viable && viable.clone().all(|fact| fact.mandatory_start_anchor);
                let mandatory_end_anchor =
                    has_viable && viable.all(|fact| fact.mandatory_end_anchor);

                PatternFact {
                    leading_symbols,
                    structural_info: PatternStructuralInfo::from_alternation_children(
                        &child_info,
                    ),
                    mandatory_start_anchor,
                    mandatory_end_anchor,
                    impossible_anchor,
                }
            }
            Pattern::Repetition(inner, quantifier) => {
                let inner_fact = self.fact(inner);
                let required = quantifier.min_repetitions() > 0;
                let impossible_anchor = if !required {
                    None
                } else if inner_fact.impossible_anchor.is_some() {
                    inner_fact.impossible_anchor
                } else if quantifier.min_repetitions() >= 2
                    && inner_fact.structural_info.min_match_rows() > 0
                    && (inner_fact.mandatory_start_anchor
                        || inner_fact.mandatory_end_anchor)
                {
                    Some(
                        "Required repetitions consume rows between mandatory partition anchors"
                            .to_string(),
                    )
                } else {
                    None
                };
                PatternFact {
                    leading_symbols: inner_fact.leading_symbols,
                    structural_info: PatternStructuralInfo::from_repetition_child(
                        inner_fact.structural_info,
                        quantifier,
                    ),
                    mandatory_start_anchor: required && inner_fact.mandatory_start_anchor,
                    mandatory_end_anchor: required && inner_fact.mandatory_end_anchor,
                    impossible_anchor,
                }
            }
        }
    }

    fn compute_concat_fact(&self, parts: &[Pattern]) -> PatternFact {
        let child_facts = self.child_facts(parts.iter());
        let leading_symbols = Self::collect_leading_symbols(&child_facts, true);
        let child_info = child_facts
            .iter()
            .map(|fact| fact.structural_info)
            .collect::<Vec<_>>();

        let impossible_anchor = analyze_concat_anchors(&child_facts, &child_info);

        PatternFact {
            leading_symbols,
            structural_info: PatternStructuralInfo::from_concat_children(&child_info),
            mandatory_start_anchor: child_facts
                .iter()
                .any(|fact| fact.mandatory_start_anchor),
            mandatory_end_anchor: child_facts
                .iter()
                .any(|fact| fact.mandatory_end_anchor),
            impossible_anchor,
        }
    }
}

fn analyze_concat_anchors(
    child_facts: &[PatternFact],
    child_info: &[PatternStructuralInfo],
) -> Option<String> {
    let mut rows_consumed = RowsConsumed::Zero;
    let mut suffix_requires_rows = vec![false; child_facts.len()];
    let mut required_after = false;
    for idx in (0..child_facts.len()).rev() {
        suffix_requires_rows[idx] = required_after;
        required_after |= child_info[idx].min_match_rows() > 0;
    }

    for (idx, fact) in child_facts.iter().enumerate() {
        if let Some(reason) = &fact.impossible_anchor {
            return Some(reason.clone());
        }
        if fact.mandatory_start_anchor && !rows_consumed.could_be_zero() {
            return Some(format!(
                "Mandatory start anchor (^) in child {idx} but one or more rows already consumed"
            ));
        }
        if fact.mandatory_end_anchor && suffix_requires_rows[idx] {
            return Some(format!(
                "Mandatory end anchor ($) in child {idx} but one or more rows required after"
            ));
        }

        rows_consumed = rows_consumed.after(child_info[idx].min_match_rows());
    }

    None
}

impl<'a> PatternOptimizer<'a> {
    /// Create a new optimizer with the given symbol status map.
    pub fn new(symbol_status: &'a HashMap<String, SymbolStatus>) -> Self {
        let mut normalized_symbol_status = HashMap::with_capacity(symbol_status.len());
        for (name, status) in symbol_status {
            normalized_symbol_status
                .entry(name.to_ascii_lowercase())
                .or_insert(*status);
        }
        Self {
            symbol_status,
            normalized_symbol_status,
            normalized_disjoint_pairs: None,
            normalized_implies_pairs: None,
            allow_pruning: false,
            pattern_facts: PatternFacts::default(),
        }
    }

    /// Add disjointness information for possessive promotion.
    ///
    /// Disjoint symbol pairs indicate that the symbols never match the same row.
    /// This enables safe promotion of unbounded greedy quantifiers to possessive.
    pub fn with_disjoint_symbols(mut self, disjoint: &[(String, String)]) -> Self {
        self.normalized_disjoint_pairs = Some(
            disjoint
                .iter()
                .map(|(lhs, rhs)| normalize_unordered_pair(lhs, rhs))
                .collect(),
        );
        self
    }

    /// Add implication information for subset/superset pruning.
    ///
    /// An implication (A, B) means "A implies B" or "A is a subset of B".
    /// Any row matching A also matches B.
    /// The caller must also ensure that substituting the earlier symbol cannot
    /// change later matching decisions. Row-predicate implication alone is
    /// insufficient when later predicates distinguish labeled histories.
    pub fn with_implies_symbols(mut self, implies: &[(String, String)]) -> Self {
        self.normalized_implies_pairs = Some(
            implies
                .iter()
                .map(|(subset, superset)| {
                    (
                        normalize_symbol_name(subset),
                        normalize_symbol_name(superset),
                    )
                })
                .collect(),
        );
        self
    }

    /// Enable or disable pruning of impossible branches.
    ///
    /// When enabled, branches that are known to never match (based on symbol
    /// status) will be removed from the pattern. This should only be enabled
    /// when the symbol status represents the entire partition.
    pub fn with_allow_pruning(mut self, allow: bool) -> Self {
        self.allow_pruning = allow;
        self
    }

    /// Optimize a pattern and return its public normalized form.
    pub fn optimize(&self, pattern: &Pattern) -> NormalizedPattern {
        // Only this immutable normalized root owns memoized node addresses.
        let pattern = normalize_symbol_and_anchor_runs(pattern.clone());
        self.pattern_facts.index_root(&pattern);

        let result = self.optimize_with_context(&pattern, &[], true, RowsConsumed::Zero);

        // Release cached addresses before the root is dropped or the optimizer reused.
        self.pattern_facts.clear();

        // Duplicate removal or complete-scope pruning can expose a named-symbol
        // run. This pass uses no cached facts and preserves the anchors left by
        // optimization.
        match result {
            NormalizedPattern::Ast(pattern) => match normalize_symbol_runs(pattern) {
                Pattern::Concat(parts) if parts.is_empty() => NormalizedPattern::Epsilon,
                pattern => NormalizedPattern::Ast(pattern),
            },
            other => other,
        }
    }

    /// Optimize with the following symbols and any proven consuming prefix.
    pub(super) fn optimize_with_context(
        &self,
        pattern: &Pattern,
        following_symbols: &[String],
        suffix_can_match_empty: bool,
        rows_before: RowsConsumed,
    ) -> NormalizedPattern {
        if !rows_before.could_be_zero()
            && matches!(
                pattern,
                Pattern::Symbol(Symbol::Start) | Pattern::Exclude(Symbol::Start)
            )
        {
            log::debug!("Start anchor cannot match after a required consuming prefix");
            return NormalizedPattern::Never;
        }

        // Structural anchor impossibilities do not depend on input data or the
        // caller's pruning setting.
        let fact = self.pattern_facts.fact(pattern);
        if let Some(reason) = fact.impossible_anchor {
            log::debug!("Structurally impossible anchor detected: {reason}");
            return NormalizedPattern::Never;
        }

        let result = match pattern {
            Pattern::Symbol(sym) => self.optimize_symbol(sym, Pattern::Symbol),
            Pattern::Exclude(sym) => self.optimize_symbol(sym, Pattern::Exclude),
            Pattern::Permute(syms) => self.optimize_permute(syms),
            Pattern::Concat(pats) => self.optimize_concat(
                pats,
                following_symbols,
                suffix_can_match_empty,
                rows_before,
                fact.structural_info.has_anchors(),
            ),
            Pattern::Group(_) => {
                unreachable!("normalize_symbol_runs strips Pattern::Group")
            }
            Pattern::Alternation(pats) => self.optimize_alternation(
                pats,
                following_symbols,
                suffix_can_match_empty,
                rows_before,
            ),
            Pattern::Repetition(pat, quant) => self.optimize_repetition(
                pat.as_ref(),
                quant,
                following_symbols,
                suffix_can_match_empty,
                rows_before,
            ),
        };

        // Child pruning can reveal mandatory anchors in every wrapper, such
        // as A (^|B) or (^ A|B){2} after removing B. Recheck changed anchored
        // trees only; ordinary unanchored patterns keep the indexed fast path.
        if fact.structural_info.has_anchors()
            && let NormalizedPattern::Ast(optimized) = &result
            && optimized != pattern
            && let Some(reason) = self.pattern_facts.fact(optimized).impossible_anchor
        {
            log::debug!(
                "Structurally impossible anchor exposed by optimization: {reason}"
            );
            return NormalizedPattern::Never;
        }
        result
    }
}

pub(crate) fn normalize_symbol_name(name: &str) -> String {
    name.to_ascii_lowercase()
}

pub(crate) fn normalize_unordered_pair(lhs: &str, rhs: &str) -> (String, String) {
    let lhs = normalize_symbol_name(lhs);
    let rhs = normalize_symbol_name(rhs);
    if lhs <= rhs { (lhs, rhs) } else { (rhs, lhs) }
}

impl<'a> PatternOptimizer<'a> {
    pub(crate) fn symbols_are_disjoint(&self, lhs: &str, rhs: &str) -> bool {
        self.normalized_disjoint_pairs
            .as_ref()
            .is_some_and(|pairs| pairs.contains(&normalize_unordered_pair(lhs, rhs)))
    }

    pub(crate) fn symbol_implies(&self, subset: &str, superset: &str) -> bool {
        self.normalized_implies_pairs.as_ref().is_some_and(|pairs| {
            let normalized_subset = normalize_symbol_name(subset);
            let normalized_superset = normalize_symbol_name(superset);
            pairs.contains(&(normalized_subset, normalized_superset))
        })
    }
}