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

//! Precomputes match-independent parts of `DEFINE` conditions.
//!
//! The input projection calculates a static expression once per row and the
//! matcher reads its generated column. A pattern-qualified column, candidate
//! navigation or aggregate, generated match-state column, or fixed match
//! metadata makes an expression depend on candidate state.
//!
//! `PREV(price)` and `NEXT(price)` are partition-level navigation and are
//! static. Within `DEFINE A`, the corresponding `A`-qualified calls are
//! rewritten to the same forms. `PREV(B.price)` and `NEXT(B.price)` still depend
//! on the rows assigned to `B`, so they are not static.
//!
//! A leading Boolean extraction can rule out a symbol match when `BooleanAnd`
//! is false or confirm one when `BooleanOr` is true. Its verdict must decide
//! the complete predicate without skipping earlier terms. Opposite Boolean
//! nesting, negative polarity, and scalar/comparison operands can block that
//! shortcut. Inline Boolean terms retain their evaluation order. Scalar
//! extraction replaces comparison operands with prepared values. Fallible
//! scalar operations and volatile calls stay in the candidate expression.

use crate::core::{
    static_predicate_and_col_name, static_predicate_or_col_name, static_scalar_col_name,
};
pub(crate) use crate::planning::define::{StaticAnalysis, is_static};
use crate::planning::expr_safety::can_precompute;
use datafusion::arrow::datatypes::DataType;
use datafusion::common::DFSchema;
use datafusion::logical_expr::{BinaryExpr, Expr, ExprSchemable, Operator};
#[cfg(test)]
use std::collections::BTreeSet;
use std::collections::HashMap;

/// The kind of static extraction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExtractionKind {
    /// A false value rejects the complete `AND` predicate.
    BooleanAnd,
    /// A true value accepts the complete `OR` predicate.
    BooleanOr,
    /// A static scalar used by a comparison that depends on candidate state.
    Scalar,
}

/// One match-independent subexpression and its generated input column.
#[derive(Debug, Clone)]
pub struct StaticExtraction {
    /// Unique column name (for example `__mr_static_predicate_and_0`,
    /// `__mr_static_predicate_or_0`, or `__mr_static_scalar_0`).
    pub column_name: String,
    /// The static expression to pre-compute.
    pub expr: Expr,
    /// Whether this is a boolean or scalar extraction.
    pub kind: ExtractionKind,
    /// Pattern variables that may use this value for runtime short-circuiting.
    pub symbols: Vec<String>,
}

/// Collects extractions across all variables and reuses identical nonvolatile expressions.
pub struct ExtractionContext<'a> {
    input_schema: &'a DFSchema,
    bool_and_counter: usize,
    bool_or_counter: usize,
    scalar_counter: usize,
    seen: HashMap<(ExtractionKind, Expr), usize>,
    /// All extractions collected so far.
    pub extractions: Vec<StaticExtraction>,
}

impl<'a> ExtractionContext<'a> {
    /// Create a new extraction context.
    pub fn new(input_schema: &'a DFSchema) -> Self {
        Self {
            input_schema,
            bool_and_counter: 0,
            bool_or_counter: 0,
            scalar_counter: 0,
            seen: HashMap::new(),
            extractions: Vec::new(),
        }
    }

    fn can_prepare(&self, expr: &Expr) -> bool {
        !expr.is_volatile()
            && can_precompute(expr, self.input_schema)
            && !crate::planning::define::preparation::expr_can_produce_undeclared_nulls(
                expr,
                self.input_schema,
            )
    }

    /// Return a generated column, sharing equal nonvolatile extraction meanings.
    fn get_or_create_extraction(
        &mut self,
        expr: &Expr,
        kind: ExtractionKind,
        symbol: &str,
    ) -> String {
        let key = (kind, expr.clone());
        if let Some(&index) = self.seen.get(&key) {
            let extraction = &mut self.extractions[index];
            if !extraction.symbols.iter().any(|known| known == symbol) {
                extraction.symbols.push(symbol.to_string());
            }
            return extraction.column_name.clone();
        }

        let col_name = match kind {
            ExtractionKind::BooleanAnd => {
                let name = static_predicate_and_col_name(self.bool_and_counter);
                self.bool_and_counter += 1;
                name
            }
            ExtractionKind::BooleanOr => {
                let name = static_predicate_or_col_name(self.bool_or_counter);
                self.bool_or_counter += 1;
                name
            }
            ExtractionKind::Scalar => {
                let name = static_scalar_col_name(self.scalar_counter);
                self.scalar_counter += 1;
                name
            }
        };

        let index = self.extractions.len();
        self.extractions.push(StaticExtraction {
            column_name: col_name.clone(),
            expr: expr.clone(),
            kind,
            symbols: vec![symbol.to_string()],
        });
        self.seen.insert(key, index);
        col_name
    }
}

/// Return whether extraction would only replace a literal, column, or casts
/// around one of those leaves.
///
/// Such a replacement would add a column without avoiding meaningful work.
fn is_literal_or_column_cast_chain(expr: &Expr) -> bool {
    match expr {
        Expr::Column(_) | Expr::Literal(_, _) => true,
        Expr::Cast(cast) => is_literal_or_column_cast_chain(&cast.expr),
        Expr::TryCast(cast) => is_literal_or_column_cast_chain(&cast.expr),
        _ => false,
    }
}

/// Replace useful static parts of one `DEFINE` condition with generated columns.
///
/// Leading preparable static terms of an eligible `AND` or `OR` chain form one
/// extraction. Preparable scalar operands are extracted separately. `ctx`
/// deduplicates nonvolatile expressions across calls and records which pattern
/// variable uses each one.
pub fn extract_static_subexpressions(
    expr: Expr,
    analysis: StaticAnalysis<'_>,
    ctx: &mut ExtractionContext<'_>,
    symbol: &str,
) -> Expr {
    // A fully static DEFINE is already calculated as one __mr_symbol_* column.
    // Adding smaller static columns would duplicate that work.
    if is_static(&expr, analysis) {
        return expr;
    }

    extract_from_expr(expr, analysis, ctx, symbol, ExtractionNesting::default())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BooleanChainKind {
    And,
    Or,
}

impl BooleanChainKind {
    fn operator(self) -> Operator {
        match self {
            Self::And => Operator::And,
            Self::Or => Operator::Or,
        }
    }

    fn combine(self, exprs: Vec<Expr>) -> Option<Expr> {
        match self {
            Self::And => exprs.into_iter().reduce(Expr::and),
            Self::Or => exprs.into_iter().reduce(Expr::or),
        }
    }

    fn extraction_kind(self) -> ExtractionKind {
        match self {
            Self::And => ExtractionKind::BooleanAnd,
            Self::Or => ExtractionKind::BooleanOr,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ExtractionNesting {
    inside_or: bool,
    inside_and: bool,
    positive_polarity: bool,
    follows_boolean_term: bool,
}

impl Default for ExtractionNesting {
    fn default() -> Self {
        Self {
            inside_or: false,
            inside_and: false,
            positive_polarity: true,
            follows_boolean_term: false,
        }
    }
}

impl ExtractionNesting {
    fn enter(self, kind: BooleanChainKind) -> Self {
        match kind {
            BooleanChainKind::And => Self {
                inside_and: true,
                ..self
            },
            BooleanChainKind::Or => Self {
                inside_or: true,
                ..self
            },
        }
    }

    fn negated(self) -> Self {
        // De Morgan duality turns surrounding disjunctions into conjunctions
        // and vice versa across NOT, so swap the nesting barriers with polarity.
        Self {
            inside_or: self.inside_and,
            inside_and: self.inside_or,
            positive_polarity: !self.positive_polarity,
            ..self
        }
    }

    fn after_boolean_term(self) -> Self {
        Self {
            follows_boolean_term: true,
            ..self
        }
    }

    fn scalar_operand(self) -> Self {
        // An operand's truth value does not decide its surrounding scalar
        // expression. Both barriers persist through NOT, unlike polarity.
        Self {
            inside_or: true,
            inside_and: true,
            ..self
        }
    }

    fn allows_boolean_extraction(self, kind: BooleanChainKind) -> bool {
        self.positive_polarity
            && !self.follows_boolean_term
            && match kind {
                BooleanChainKind::And => !self.inside_or,
                BooleanChainKind::Or => !self.inside_and,
            }
    }
}

fn extract_from_expr(
    expr: Expr,
    analysis: StaticAnalysis<'_>,
    ctx: &mut ExtractionContext<'_>,
    symbol: &str,
    nesting: ExtractionNesting,
) -> Expr {
    // A Boolean extraction needs to decide the complete predicate without
    // bypassing earlier evaluation. Keep both constraints during recursion.

    match expr {
        expr @ Expr::BinaryExpr(BinaryExpr {
            op: Operator::And, ..
        }) => handle_boolean_chain(
            expr,
            analysis,
            ctx,
            symbol,
            nesting,
            BooleanChainKind::And,
        ),

        expr @ Expr::BinaryExpr(BinaryExpr {
            op: Operator::Or, ..
        }) => handle_boolean_chain(
            expr,
            analysis,
            ctx,
            symbol,
            nesting,
            BooleanChainKind::Or,
        ),

        Expr::BinaryExpr(BinaryExpr { left, op, right }) if is_comparison(op) => {
            handle_comparison(*left, op, *right, analysis, ctx, symbol, nesting)
        }

        Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
            let nesting = nesting.scalar_operand();
            let new_left = extract_from_expr(*left, analysis, ctx, symbol, nesting);
            let new_right = extract_from_expr(*right, analysis, ctx, symbol, nesting);
            Expr::BinaryExpr(BinaryExpr {
                left: Box::new(new_left),
                op,
                right: Box::new(new_right),
            })
        }

        Expr::Not(inner) => {
            let new_inner =
                extract_from_expr(*inner, analysis, ctx, symbol, nesting.negated());
            Expr::Not(Box::new(new_inner))
        }

        expr => expr,
    }
}

/// Replace a useful static side of a comparison with its generated column.
///
/// For example, `COUNT(A.*) < (price * tax)` reads a generated column for
/// `price * tax` while leaving the match-aware aggregate in place.
fn handle_comparison(
    left: Expr,
    op: Operator,
    right: Expr,
    analysis: StaticAnalysis<'_>,
    ctx: &mut ExtractionContext<'_>,
    symbol: &str,
    nesting: ExtractionNesting,
) -> Expr {
    let nesting = nesting.scalar_operand();
    let left_static = is_static(&left, analysis);
    let right_static = is_static(&right, analysis);

    if left_static && right_static {
        return Expr::BinaryExpr(BinaryExpr {
            left: Box::new(left),
            op,
            right: Box::new(right),
        });
    }

    let mut rewrite_side = |side: Expr, is_side_static: bool| {
        if !is_side_static {
            extract_from_expr(side, analysis, ctx, symbol, nesting)
        } else if !is_literal_or_column_cast_chain(&side) && ctx.can_prepare(&side) {
            let name =
                ctx.get_or_create_extraction(&side, ExtractionKind::Scalar, symbol);
            Expr::Column(datafusion::common::Column::from_name(name))
        } else {
            side
        }
    };

    // Register the static extraction before recursing into its match-aware sibling.
    let (new_left, new_right) = if right_static {
        let right = rewrite_side(right, true);
        (rewrite_side(left, false), right)
    } else {
        (rewrite_side(left, left_static), rewrite_side(right, false))
    };

    Expr::BinaryExpr(BinaryExpr {
        left: Box::new(new_left),
        op,
        right: Box::new(new_right),
    })
}

/// Extract a leading static guard while keeping Boolean terms in operand order.
fn handle_boolean_chain(
    expr: Expr,
    analysis: StaticAnalysis<'_>,
    ctx: &mut ExtractionContext<'_>,
    symbol: &str,
    nesting: ExtractionNesting,
    kind: BooleanChainKind,
) -> Expr {
    let mut children = boolean_terms(&expr, kind.operator()).cloned().peekable();
    let mut result_children = Vec::new();
    if nesting.allows_boolean_extraction(kind) {
        let mut prefix = Vec::new();
        while let Some(child) = children.next_if(|child| {
            is_static(child, analysis)
                && ctx.can_prepare(child)
                && matches!(child.get_type(ctx.input_schema), Ok(DataType::Boolean))
        }) {
            prefix.push(child);
        }
        if let Some(prefix) = kind.combine(prefix) {
            let guard = if is_literal_or_column_cast_chain(&prefix) {
                prefix
            } else {
                let column =
                    ctx.get_or_create_extraction(&prefix, kind.extraction_kind(), symbol);
                Expr::Column(datafusion::common::Column::from_name(column))
            };
            result_children.push(guard);
        }
    }

    let mut child_nesting = nesting.enter(kind);
    if !result_children.is_empty() {
        child_nesting = child_nesting.after_boolean_term();
    }
    for child in children {
        let child = if is_static(&child, analysis) {
            child
        } else {
            extract_from_expr(child, analysis, ctx, symbol, child_nesting)
        };
        result_children.push(child);
        child_nesting = child_nesting.after_boolean_term();
    }

    kind.combine(result_children)
        .expect("binary boolean chain retains at least one child")
}

/// Visit one Boolean chain in operand order without descending through aliases,
/// negation, or a different operator.
pub(crate) fn boolean_terms(expr: &Expr, op: Operator) -> impl Iterator<Item = &Expr> {
    let mut stack = vec![expr];
    std::iter::from_fn(move || {
        while let Some(current) = stack.pop() {
            if let Expr::BinaryExpr(binary) = current
                && binary.op == op
            {
                stack.push(&binary.right);
                stack.push(&binary.left);
            } else {
                return Some(current);
            }
        }
        None
    })
}

pub(crate) fn is_comparison(op: Operator) -> bool {
    matches!(
        op,
        Operator::Eq
            | Operator::NotEq
            | Operator::Lt
            | Operator::LtEq
            | Operator::Gt
            | Operator::GtEq
    )
}

#[cfg(test)]
mod tests;

#[cfg(test)]
mod rewrite_tests {
    use super::*;
    use crate::core::{classifier_bits_col_name, managed_aggregate_col_name};
    use datafusion::arrow::datatypes::{Field, Schema};
    use datafusion::common::ScalarValue;
    use datafusion::logical_expr::{col, expr::Case, lit};
    use std::collections::BTreeSet;

    #[test]
    fn null_typed_leading_boolean_terms_are_not_extracted_as_boolean_slots() {
        let schema = DFSchema::try_from(Schema::new(vec![
            Field::new("flag", DataType::Boolean, true),
            Field::new("price", DataType::Float64, true),
        ]))
        .expect("schema");
        let generated = BTreeSet::from([
            classifier_bits_col_name("A"),
            managed_aggregate_col_name(0),
        ]);
        let analysis = StaticAnalysis::new(&generated);

        let null_case = Expr::Case(Case::new(
            None,
            vec![(Box::new(col("flag")), Box::new(lit(ScalarValue::Null)))],
            None,
        ));
        let null_coalesce = datafusion::functions::core::coalesce()
            .call(vec![lit(ScalarValue::Null), lit(ScalarValue::Null)]);
        let candidate = col(managed_aggregate_col_name(0)).gt_eq(lit(2_i64));

        for (label, null_term) in [
            ("CASE WHEN flag THEN NULL END", null_case.clone()),
            ("COALESCE(NULL, NULL)", null_coalesce),
        ] {
            assert_eq!(
                null_term.get_type(&schema).unwrap(),
                DataType::Null,
                "{label}"
            );
            assert!(
                can_precompute(&null_term, &schema),
                "{label} must exercise the Boolean-type guard rather than can_precompute"
            );
            for (op_label, expr) in [
                ("OR", null_term.clone().or(candidate.clone())),
                ("AND", null_term.clone().and(candidate.clone())),
            ] {
                let mut ctx = ExtractionContext::new(&schema);
                let rewritten =
                    extract_static_subexpressions(expr.clone(), analysis, &mut ctx, "A");
                assert!(ctx.extractions.is_empty(), "{label} {op_label}");
                assert_eq!(rewritten, expr, "{label} {op_label}");
            }
        }

        // A Boolean prefix before a Null-typed term still extracts only the Boolean part.
        let bool_term = col("price").gt(lit(100.0));
        let mixed = bool_term
            .clone()
            .and(null_case.clone())
            .and(candidate.clone());
        let mut ctx = ExtractionContext::new(&schema);
        let rewritten = extract_static_subexpressions(mixed, analysis, &mut ctx, "A");
        assert_eq!(ctx.extractions.len(), 1);
        assert_eq!(ctx.extractions[0].kind, ExtractionKind::BooleanAnd);
        assert_eq!(ctx.extractions[0].expr, bool_term);
        assert_eq!(
            ctx.extractions[0].expr.get_type(&schema).unwrap(),
            DataType::Boolean
        );
        assert_eq!(
            rewritten,
            col("__mr_static_predicate_and_0")
                .and(null_case)
                .and(candidate.clone())
        );

        // Positive control: a Boolean leading OR term still extracts as BooleanOr.
        let mut or_ctx = ExtractionContext::new(&schema);
        let or_rewritten = extract_static_subexpressions(
            bool_term.clone().or(candidate.clone()),
            analysis,
            &mut or_ctx,
            "A",
        );
        assert_eq!(or_ctx.extractions.len(), 1);
        assert_eq!(or_ctx.extractions[0].kind, ExtractionKind::BooleanOr);
        assert_eq!(or_ctx.extractions[0].expr, bool_term);
        assert_eq!(
            or_rewritten,
            col("__mr_static_predicate_or_0").or(candidate)
        );
    }
}

#[cfg(test)]
mod boolean_terms_tests {
    use super::*;
    use datafusion::common::ScalarValue;
    use datafusion::logical_expr::{col, lit};

    #[test]
    fn boolean_terms_preserve_order_and_boundaries() {
        let binary = |left, op, right| {
            Expr::BinaryExpr(BinaryExpr::new(Box::new(left), op, Box::new(right)))
        };
        for (op, other) in [(Operator::And, Operator::Or), (Operator::Or, Operator::And)]
        {
            let terms = vec![
                col("a"),
                binary(col("b"), op, col("c")).alias("group"),
                binary(col("d"), other, col("e")),
                Expr::Not(Box::new(binary(col("f"), op, col("g")))),
                lit(ScalarValue::Boolean(None)),
                col("a"),
            ];
            let left = terms
                .iter()
                .cloned()
                .reduce(|l, r| binary(l, op, r))
                .unwrap();
            let right = terms
                .iter()
                .rev()
                .cloned()
                .reduce(|r, l| binary(l, op, r))
                .unwrap();
            for expr in [left, right] {
                assert_eq!(boolean_terms(&expr, op).cloned().collect::<Vec<_>>(), terms);
            }
        }
    }
}