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

//! Facts the planner can learn from `DEFINE` conditions without running them.
//!
//! The relationship analysis detects when two pattern variables are disjoint or
//! imply one another (including mutual implication when equivalent).

use crate::core::{MatchMetadataColumn, classifier_bits_col_name};
use crate::planning::NamedExpr;
use datafusion::arrow::datatypes::DataType;
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::TreeNode;
use datafusion::common::{DFSchemaRef, ScalarValue};
use datafusion::logical_expr::simplify::SimplifyContext;
use datafusion::logical_expr::{Expr, ExprSchemable, Operator, Volatility};
use datafusion_optimizer::simplify_expressions::ExprSimplifier;
use std::sync::Arc;

/// Relationships the planner found between all pairs of pattern variables.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct SymbolRelationships {
    /// Pairs of symbols whose predicates cannot both be true.
    pub disjoint: Vec<(String, String)>,
    /// Ordered `(implying, implied)` symbol pairs.
    pub implies: Vec<(String, String)>,
}

/// Result of analyzing relationships between two predicates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PredicateRelationship {
    /// The predicates cannot both be true.
    Disjoint,
    /// The left predicate implies the right predicate.
    Implies,
    /// The right predicate implies the left predicate.
    ImpliedBy,
    /// The predicates imply each other.
    Equivalent,
    /// No supported relationship was detected.
    Unknown,
}

/// Simplified condition facts reused by implication and disjointness checks.
struct PredicatePairAnalysis<'a> {
    simplifier: &'a ExprSimplifier,
    lhs: &'a Expr,
    rhs: &'a Expr,
    lhs_conjuncts: Vec<&'a Expr>,
    rhs_conjuncts: Vec<&'a Expr>,
    rhs_disjuncts: Vec<&'a Expr>,
}

impl<'a> PredicatePairAnalysis<'a> {
    fn new(lhs: &'a Expr, rhs: &'a Expr, simplifier: &'a ExprSimplifier) -> Self {
        Self {
            simplifier,
            lhs,
            rhs,
            lhs_conjuncts: split_and(lhs),
            rhs_conjuncts: split_and(rhs),
            rhs_disjuncts: split_or(rhs),
        }
    }

    fn is_subset(&self) -> bool {
        if !expr_uses_symbol_dependent_metadata(self.lhs)
            && !expr_uses_symbol_dependent_metadata(self.rhs)
            && simplifies_to(
                self.lhs.clone().and(Expr::Not(Box::new(self.rhs.clone()))),
                false,
                self.simplifier,
            )
        {
            return true;
        }

        if self.rhs_disjuncts.len() > 1 {
            return self.rhs_disjuncts.iter().any(|&predicate| {
                Self::new(self.lhs, predicate, self.simplifier).is_subset()
            });
        }

        self.rhs_conjuncts.iter().all(|rhs_conjunct| {
            !expr_uses_symbol_dependent_metadata(rhs_conjunct)
                && self.lhs_conjuncts.iter().any(|lhs_conjunct| {
                    !expr_uses_symbol_dependent_metadata(lhs_conjunct)
                        && is_pair_subset(lhs_conjunct, rhs_conjunct, self.simplifier)
                })
        })
    }
}

/// Safe facts extracted from one `DEFINE` predicate for relationship proofs.
struct AnalyzedPredicate {
    /// Coerced and simplified whole predicate, present only when the entire
    /// expression is a total, non-volatile, match-independent scalar. Required
    /// for implication/equivalence proofs because pruning a subset branch skips
    /// it even on rows that satisfy its leading conjuncts.
    whole_safe: Option<Expr>,
    /// Coerced and simplified leading prefix of top-level `AND` conjuncts that
    /// are total, non-volatile, symbol-independent Boolean scalars. Safe for
    /// disjointness proofs because earlier conjuncts cannot fail or invoke
    /// stateful/volatile work before the contradicting leading guard rejects.
    leading_safe_expr: Option<Expr>,
    leading_safe_conjuncts: Vec<Expr>,
}

/// Return whether an expression references metadata whose value depends on the
/// candidate symbol being tested on the current row.
fn expr_uses_symbol_dependent_metadata(expr: &Expr) -> bool {
    let classifier_prefix = classifier_bits_col_name("");
    expr.exists(|node| {
        let Expr::Column(column) = node else {
            return Ok(false);
        };
        Ok(matches!(
            column.name.parse::<MatchMetadataColumn>(),
            Ok(MatchMetadataColumn::Classifier | MatchMetadataColumn::Excluded)
        ) || column.name.starts_with(classifier_prefix.as_str()))
    })
    .unwrap_or(true)
}

/// Return whether an expression contains volatile calls, query-dependent
/// constants, or subqueries that the simplifier must not evaluate.
fn expr_is_context_dependent(expr: &Expr) -> bool {
    expr.exists(|node| {
        Ok(match node {
            Expr::ScalarFunction(f) => {
                f.func.signature().volatility != Volatility::Immutable
            }
            Expr::AggregateFunction(f) => {
                f.func.signature().volatility != Volatility::Immutable
            }
            Expr::WindowFunction(f) => {
                f.fun.signature().volatility != Volatility::Immutable
            }
            Expr::ScalarSubquery(_) | Expr::Exists(_) | Expr::InSubquery(_) => true,
            _ => false,
        })
    })
    .unwrap_or(true)
}

fn are_leading_prefixes_disjoint(
    lhs: &AnalyzedPredicate,
    rhs: &AnalyzedPredicate,
    simplifier: &ExprSimplifier,
) -> bool {
    let (Some(lhs_expr), Some(rhs_expr)) =
        (&lhs.leading_safe_expr, &rhs.leading_safe_expr)
    else {
        return false;
    };
    if simplifies_to(lhs_expr.clone().and(rhs_expr.clone()), false, simplifier) {
        return true;
    }
    lhs.leading_safe_conjuncts.iter().any(|lhs_conjunct| {
        rhs.leading_safe_conjuncts
            .iter()
            .any(|rhs_conjunct| is_pair_disjoint(lhs_conjunct, rhs_conjunct, simplifier))
    })
}

fn analyze_predicate_relationship(
    lhs: &AnalyzedPredicate,
    rhs: &AnalyzedPredicate,
    simplifier: &ExprSimplifier,
) -> PredicateRelationship {
    let (a_implies_b, b_implies_a) = match (&lhs.whole_safe, &rhs.whole_safe) {
        (Some(expr_a), Some(expr_b)) => (
            PredicatePairAnalysis::new(expr_a, expr_b, simplifier).is_subset(),
            PredicatePairAnalysis::new(expr_b, expr_a, simplifier).is_subset(),
        ),
        _ => (false, false),
    };

    match (a_implies_b, b_implies_a) {
        (true, true) => PredicateRelationship::Equivalent,
        (true, false) => PredicateRelationship::Implies,
        (false, true) => PredicateRelationship::ImpliedBy,
        (false, false) if are_leading_prefixes_disjoint(lhs, rhs, simplifier) => {
            PredicateRelationship::Disjoint
        }
        (false, false) => PredicateRelationship::Unknown,
    }
}

/// Analyze predicates using their input types; unsupported proofs remain unknown.
pub fn analyze_all_symbol_relationships(
    defines: &[NamedExpr],
    schema: &DFSchemaRef,
    options: &ConfigOptions,
) -> SymbolRelationships {
    let mut result = SymbolRelationships::default();
    if defines.len() < 2 {
        return result;
    }
    let simplifier = ExprSimplifier::new(
        SimplifyContext::builder()
            .with_schema(Arc::clone(schema))
            .with_config_options(Arc::new(options.clone()))
            .build(),
    );
    let predicates = defines
        .iter()
        .map(|define| {
            // Proofs must not evaluate volatile calls, query-dependent constants,
            // or fallible scalar operations whose errors could be suppressed.
            let whole_safe = if !expr_is_context_dependent(&define.expr)
                && crate::planning::expr_safety::can_discard_scalar(
                    &define.expr,
                    Some(schema.as_ref()),
                ) {
                simplifier
                    .coerce(define.expr.clone(), schema)
                    .ok()
                    .and_then(|expr| {
                        expr.get_type(schema).ok()?;
                        simplifier.simplify(expr).ok()
                    })
            } else {
                None
            };

            let mut leading_safe_conjuncts = Vec::new();
            for conjunct in split_and(&define.expr) {
                if expr_is_context_dependent(conjunct)
                    || expr_uses_symbol_dependent_metadata(conjunct)
                    || !crate::planning::expr_safety::can_discard_scalar(
                        conjunct,
                        Some(schema.as_ref()),
                    )
                {
                    break;
                }
                let Ok(coerced) = simplifier.coerce(conjunct.clone(), schema) else {
                    break;
                };
                if !matches!(coerced.get_type(schema), Ok(DataType::Boolean)) {
                    break;
                }
                let Ok(simplified) = simplifier.simplify(coerced) else {
                    break;
                };
                for part in split_and(&simplified) {
                    leading_safe_conjuncts.push(part.clone());
                }
            }
            let leading_safe_expr =
                leading_safe_conjuncts.iter().cloned().reduce(Expr::and);

            AnalyzedPredicate {
                whole_safe,
                leading_safe_expr,
                leading_safe_conjuncts,
            }
        })
        .collect::<Vec<_>>();

    for (i, def1) in defines.iter().enumerate() {
        for (j, def2) in defines.iter().enumerate().skip(i + 1) {
            match analyze_predicate_relationship(
                &predicates[i],
                &predicates[j],
                &simplifier,
            ) {
                PredicateRelationship::Disjoint => {
                    result.disjoint.push((def1.name.clone(), def2.name.clone()));
                }
                PredicateRelationship::Implies => {
                    result.implies.push((def1.name.clone(), def2.name.clone()));
                }
                PredicateRelationship::ImpliedBy => {
                    result.implies.push((def2.name.clone(), def1.name.clone()));
                }
                PredicateRelationship::Equivalent => {
                    result.implies.push((def1.name.clone(), def2.name.clone()));
                    result.implies.push((def2.name.clone(), def1.name.clone()));
                }
                PredicateRelationship::Unknown => {}
            }
        }
    }

    result
}

fn simplifies_to(expr: Expr, value: bool, simplifier: &ExprSimplifier) -> bool {
    matches!(
        simplifier.simplify(expr),
        Ok(Expr::Literal(ScalarValue::Boolean(Some(actual)), _)) if actual == value
    )
}

type NormalizedComparison<'a> = (&'a Expr, Operator, &'a Expr);

pub(super) fn is_pair_disjoint(
    expr1: &Expr,
    expr2: &Expr,
    simplifier: &ExprSimplifier,
) -> bool {
    let Some((left1, op1, right1)) = normalized_binary_comparison(expr1) else {
        return false;
    };
    let Some((left2, op2, right2)) = normalized_binary_comparison(expr2) else {
        return false;
    };

    if left1 != left2 {
        return false;
    }

    if right1 == right2 {
        return disjoint_operators(op1, op2);
    }

    let comparison = match (op1, op2) {
        (Operator::Eq, Operator::Eq) => Operator::NotEq,
        (Operator::LtEq, Operator::GtEq | Operator::Eq)
        | (Operator::Eq, Operator::GtEq) => Operator::Lt,
        (Operator::Lt, Operator::Gt | Operator::GtEq | Operator::Eq)
        | (Operator::LtEq | Operator::Eq, Operator::Gt) => Operator::LtEq,
        (Operator::GtEq, Operator::LtEq | Operator::Eq)
        | (Operator::Eq, Operator::LtEq) => Operator::Gt,
        (Operator::Gt, Operator::Lt | Operator::LtEq | Operator::Eq)
        | (Operator::GtEq | Operator::Eq, Operator::Lt) => Operator::GtEq,
        _ => return false,
    };
    compare_literals(right1, comparison, right2, simplifier)
}

pub(super) fn is_pair_subset(
    expr_a: &Expr,
    expr_b: &Expr,
    simplifier: &ExprSimplifier,
) -> bool {
    if expr_a == expr_b {
        return true;
    }

    let Some((left1, op1, right1)) = normalized_binary_comparison(expr_a) else {
        return false;
    };

    // DataFusion can retain numeric equality alternatives as literal IN lists.
    // Primitive float equality and literal IN both equate the two zero signs
    // and compare NaNs by their bits.
    if let Expr::InList(in_list) = strip_alias(expr_b)
        && !in_list.negated
        && op1 == Operator::Eq
        && matches!(left1, Expr::Column(_))
        && left1 == strip_alias(&in_list.expr)
        && let Expr::Literal(value, _) = right1
        && (value.data_type().is_integer() || value.data_type().is_floating())
        && in_list
            .list
            .iter()
            .all(|value| matches!(strip_alias(value), Expr::Literal(..)))
    {
        return in_list.list.iter().any(|value| {
            compare_literals(right1, Operator::Eq, strip_alias(value), simplifier)
        });
    }

    let Some((left2, op2, right2)) = normalized_binary_comparison(expr_b) else {
        return false;
    };

    if left1 != left2 {
        return false;
    }

    if right1 == right2 {
        return matches!(
            (op1, op2),
            (Operator::Eq, Operator::LtEq | Operator::GtEq)
                | (Operator::Lt, Operator::LtEq)
                | (Operator::Gt, Operator::GtEq)
        );
    }

    let comparison =
        match (op1, op2) {
            (Operator::Lt | Operator::Eq, Operator::LtEq)
            | (Operator::Lt, Operator::Lt) => Operator::LtEq,
            (Operator::LtEq | Operator::Eq, Operator::Lt) => Operator::Lt,
            (Operator::Gt | Operator::Eq, Operator::GtEq)
            | (Operator::Gt, Operator::Gt) => Operator::GtEq,
            (Operator::GtEq | Operator::Eq, Operator::Gt) => Operator::Gt,
            (Operator::LtEq, Operator::LtEq) => Operator::LtEq,
            (Operator::GtEq, Operator::GtEq) => Operator::GtEq,
            _ => return false,
        };
    compare_literals(right1, comparison, right2, simplifier)
}

fn normalized_binary_comparison(expr: &Expr) -> Option<NormalizedComparison<'_>> {
    let Expr::BinaryExpr(binary) = strip_alias(expr) else {
        return None;
    };
    let left = strip_alias(&binary.left);
    let right = strip_alias(&binary.right);
    let op = binary.op;
    let swap = match (left, right) {
        (Expr::Column(left), Expr::Column(right)) => left > right,
        (_, Expr::Column(_)) => true,
        _ => false,
    };
    Some(if swap {
        (right, op.swap().unwrap_or(op), left)
    } else {
        (left, op, right)
    })
}

fn disjoint_operators(op1: Operator, op2: Operator) -> bool {
    matches!(
        (op1, op2),
        (Operator::Lt, Operator::Gt)
            | (Operator::Lt, Operator::GtEq)
            | (Operator::LtEq, Operator::Gt)
            | (Operator::Gt, Operator::Lt)
            | (Operator::Gt, Operator::LtEq)
            | (Operator::GtEq, Operator::Lt)
            | (Operator::Eq, Operator::NotEq)
            | (Operator::NotEq, Operator::Eq)
            // Strict inequalities are disjoint from equality at the same boundary.
            | (Operator::Lt, Operator::Eq)
            | (Operator::Eq, Operator::Lt)
            | (Operator::Gt, Operator::Eq)
            | (Operator::Eq, Operator::Gt)
    )
}

fn compare_literals(
    left: &Expr,
    op: Operator,
    right: &Expr,
    simplifier: &ExprSimplifier,
) -> bool {
    let (Expr::Literal(v1, _), Expr::Literal(v2, _)) = (left, right) else {
        return false;
    };
    v1.data_type() == v2.data_type()
        && simplifies_to(
            Expr::BinaryExpr(datafusion::logical_expr::BinaryExpr::new(
                Box::new(left.clone()),
                op,
                Box::new(right.clone()),
            )),
            true,
            simplifier,
        )
}

pub(super) fn strip_alias(expr: &Expr) -> &Expr {
    if let Expr::Alias(alias) = expr {
        strip_alias(&alias.expr)
    } else {
        expr
    }
}

pub(super) fn split_and(expr: &Expr) -> Vec<&Expr> {
    split_by_operator(expr, Operator::And)
}

pub(super) fn split_or(expr: &Expr) -> Vec<&Expr> {
    split_by_operator(expr, Operator::Or)
}

fn split_by_operator(expr: &Expr, operator: Operator) -> Vec<&Expr> {
    let mut predicates = Vec::new();
    let mut stack = vec![strip_alias(expr)];

    while let Some(current) = stack.pop() {
        if let Expr::BinaryExpr(binary_expr) = current
            && binary_expr.op == operator
        {
            stack.push(strip_alias(&binary_expr.right));
            stack.push(strip_alias(&binary_expr.left));
            continue;
        }
        predicates.push(current);
    }

    predicates
}

#[cfg(test)]
#[path = "symbol_relationships_tests.rs"]
mod tests;