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

//! Recognizes match metadata that is part of an aggregate's SQL meaning.

use std::str::FromStr;

use crate::core::{MatchMetadataColumn, classifier_bits_col_name};
use datafusion::common::tree_node::TreeNode;
use datafusion::logical_expr::expr::{AggregateFunction, WindowFunction};
use datafusion::logical_expr::{Expr, SortExpr, WindowFunctionDefinition};

use crate::planning::logical::is_internal_sequence_ordering;
use crate::planning::navigation_names::NavigationFunctionFamily;

/// Return whether an expression reads one of the four SQL-visible metadata
/// values. `PathId` is matcher-owned and is deliberately excluded.
pub(crate) fn expr_references_public_match_metadata(expr: &Expr) -> bool {
    expr.exists(|node| {
        let Expr::Column(column) = node else {
            return Ok(false);
        };
        Ok(matches!(
            MatchMetadataColumn::from_str(&column.name),
            Ok(MatchMetadataColumn::Classifier)
                | Ok(MatchMetadataColumn::MatchNumber)
                | Ok(MatchMetadataColumn::MatchSequenceNumber)
                | Ok(MatchMetadataColumn::Excluded)
        ))
    })
    .unwrap_or(false)
}

fn semantic_args_reference_metadata(
    navigation: Option<NavigationFunctionFamily>,
    args: &[Expr],
) -> bool {
    match navigation {
        Some(NavigationFunctionFamily::First | NavigationFunctionFamily::Last) => args
            .first()
            .is_some_and(expr_references_public_match_metadata),
        Some(NavigationFunctionFamily::Prev | NavigationFunctionFamily::Next) => {
            args.first()
                .is_some_and(expr_references_public_match_metadata)
                || args
                    .get(2)
                    .is_some_and(expr_references_public_match_metadata)
        }
        None => args.iter().any(expr_references_public_match_metadata),
    }
}

/// Return whether an aggregate or window `ORDER BY` is solely the canonical
/// synthetic within-match sequence ordering (`__mr_match_sequence_number ASC NULLS LAST`).
pub(crate) fn is_sole_internal_sequence_ordering(order_by: &[SortExpr]) -> bool {
    matches!(order_by, [sort] if is_internal_sequence_ordering(sort))
}

fn order_by_references_semantic_metadata(order_by: &[SortExpr]) -> bool {
    !is_sole_internal_sequence_ordering(order_by)
        && order_by
            .iter()
            .any(|sort| expr_references_public_match_metadata(&sort.expr))
}

fn call_references_semantic_metadata(
    navigation: Option<NavigationFunctionFamily>,
    args: &[Expr],
    filter: Option<&Expr>,
    order_by: &[SortExpr],
) -> bool {
    semantic_args_reference_metadata(navigation, args)
        || filter.is_some_and(expr_references_public_match_metadata)
        || order_by_references_semantic_metadata(order_by)
}

/// Return whether an expression is a bare unqualified `CLASSIFIER()` column.
pub(crate) fn is_bare_classifier_column(expr: &Expr) -> bool {
    matches!(
        expr,
        Expr::Column(column)
            if column.relation.is_none()
                && column.name == MatchMetadataColumn::Classifier.as_ref()
    )
}

fn is_managed_classifier_navigation_call(
    navigation: Option<NavigationFunctionFamily>,
    args: &[Expr],
    filter: Option<&Expr>,
    order_by: &[SortExpr],
) -> bool {
    let supported_family = matches!(
        navigation,
        Some(
            NavigationFunctionFamily::First
                | NavigationFunctionFamily::Last
                | NavigationFunctionFamily::Prev
        )
    );
    if !supported_family || !args.first().is_some_and(is_bare_classifier_column) {
        return false;
    }
    if matches!(navigation, Some(NavigationFunctionFamily::Prev))
        && args
            .get(2)
            .is_some_and(expr_references_public_match_metadata)
    {
        return false;
    }
    !filter.is_some_and(expr_references_public_match_metadata)
        && !order_by_references_semantic_metadata(order_by)
}

/// Return whether a managed aggregate is a `FIRST`/`LAST`/`PREV` navigation
/// directly over `CLASSIFIER()` that can be maintained in managed state.
pub(crate) fn is_managed_classifier_navigation_aggregate(
    aggregate: &AggregateFunction,
) -> bool {
    is_managed_classifier_navigation_call(
        NavigationFunctionFamily::from_aggregate_udf(aggregate.func.as_ref()),
        &aggregate.params.args,
        aggregate.params.filter.as_deref(),
        &aggregate.params.order_by,
    )
}

/// Return whether a match-scoped window is a `FIRST`/`LAST`/`PREV` navigation
/// directly over `CLASSIFIER()` that can be extracted as a managed aggregate.
pub(crate) fn is_managed_classifier_navigation_window(window: &WindowFunction) -> bool {
    let navigation = match &window.fun {
        WindowFunctionDefinition::AggregateUDF(udaf) => {
            NavigationFunctionFamily::from_aggregate_udf(udaf.as_ref())
        }
        WindowFunctionDefinition::WindowUDF(udwf) => {
            NavigationFunctionFamily::from_window_udf(udwf.as_ref())
        }
    };
    is_managed_classifier_navigation_call(
        navigation,
        &window.params.args,
        window.params.filter.as_deref(),
        &window.params.order_by,
    ) && !window
        .params
        .partition_by
        .iter()
        .any(expr_references_partition_semantic_metadata)
}

/// Return whether a managed aggregate reads SQL-visible match metadata.
///
/// Matcher navigation may carry structural masks and ordering alongside its
/// SQL arguments. Only its value and default positions are semantic.
pub(crate) fn aggregate_references_semantic_metadata(
    aggregate: &AggregateFunction,
) -> bool {
    call_references_semantic_metadata(
        NavigationFunctionFamily::from_aggregate_udf(aggregate.func.as_ref()),
        &aggregate.params.args,
        aggregate.params.filter.as_deref(),
        &aggregate.params.order_by,
    )
}

pub(super) fn is_structural_match_partition_column(expr: &Expr) -> bool {
    matches!(
        expr,
        Expr::Column(column)
            if column.relation.is_none()
                && matches!(
                    MatchMetadataColumn::from_str(&column.name),
                    Ok(MatchMetadataColumn::MatchNumber | MatchMetadataColumn::PathId)
                )
    )
}

fn expr_references_partition_semantic_metadata(expr: &Expr) -> bool {
    if is_structural_match_partition_column(expr) {
        return false;
    }
    let classifier_prefix = classifier_bits_col_name("");
    expr.exists(|node| {
        let Expr::Column(column) = node else {
            return Ok(false);
        };
        Ok(matches!(
            MatchMetadataColumn::from_str(&column.name),
            Ok(MatchMetadataColumn::Classifier
                | MatchMetadataColumn::MatchNumber
                | MatchMetadataColumn::MatchSequenceNumber
                | MatchMetadataColumn::Excluded)
        ) || column.name.starts_with(classifier_prefix.as_str()))
    })
    .unwrap_or(true)
}

/// Return whether a match-scoped window reads SQL-visible match metadata.
pub(crate) fn window_references_semantic_metadata(window: &WindowFunction) -> bool {
    let navigation = match &window.fun {
        WindowFunctionDefinition::AggregateUDF(udaf) => {
            NavigationFunctionFamily::from_aggregate_udf(udaf.as_ref())
        }
        WindowFunctionDefinition::WindowUDF(udwf) => {
            NavigationFunctionFamily::from_window_udf(udwf.as_ref())
        }
    };
    call_references_semantic_metadata(
        navigation,
        &window.params.args,
        window.params.filter.as_deref(),
        &window.params.order_by,
    ) || window
        .params
        .partition_by
        .iter()
        .any(expr_references_partition_semantic_metadata)
}

#[cfg(test)]
mod tests {
    use crate::core::{MatchMetadataColumn, classifier_bits_col_name};
    use datafusion::common::ScalarValue;
    use datafusion::logical_expr::expr::{
        AggregateFunction, AggregateFunctionParams, WindowFunction,
    };
    use datafusion::logical_expr::{Expr, SortExpr, WindowFunctionDefinition, col, lit};

    use super::{
        aggregate_references_semantic_metadata,
        is_managed_classifier_navigation_aggregate,
        is_managed_classifier_navigation_window, is_sole_internal_sequence_ordering,
        window_references_semantic_metadata,
    };

    fn prev(args: Vec<Expr>) -> AggregateFunction {
        AggregateFunction {
            func: crate::functions::udaf::mr_prev_udaf(),
            params: AggregateFunctionParams {
                args,
                distinct: false,
                filter: None,
                order_by: vec![SortExpr::new(
                    col(MatchMetadataColumn::MatchSequenceNumber.as_ref()),
                    true,
                    false,
                )],
                null_treatment: None,
            },
        }
    }

    #[test]
    fn navigation_checks_only_semantic_arguments() {
        let classifier = col(MatchMetadataColumn::Classifier.as_ref());
        let matcher_mask = classifier.clone().is_not_null();
        let base = vec![
            col("price"),
            lit(ScalarValue::UInt64(Some(1))),
            lit(ScalarValue::Null),
            matcher_mask.clone(),
            matcher_mask,
        ];
        assert!(!aggregate_references_semantic_metadata(&prev(base.clone())));

        let mut value_metadata = base.clone();
        value_metadata[0] = classifier.clone();
        assert!(aggregate_references_semantic_metadata(&prev(
            value_metadata
        )));

        let mut default_metadata = base;
        default_metadata[2] = classifier;
        assert!(aggregate_references_semantic_metadata(&prev(
            default_metadata
        )));
    }

    #[test]
    fn window_partition_rejects_non_structural_metadata() {
        let make_window = |partition_by: Vec<Expr>| {
            let mut window = WindowFunction::new(
                WindowFunctionDefinition::AggregateUDF(
                    datafusion::functions_aggregate::count::count_udaf(),
                ),
                vec![col("price")],
            );
            window.params.partition_by = partition_by;
            window
        };

        for structural in [
            vec![col("k"), col(MatchMetadataColumn::MatchNumber.as_ref())],
            vec![col(MatchMetadataColumn::MatchNumber.as_ref())],
            vec![col(MatchMetadataColumn::PathId.as_ref())],
        ] {
            assert!(
                !window_references_semantic_metadata(&make_window(structural.clone())),
                "{structural:?}"
            );
        }

        for semantic in [
            vec![col(MatchMetadataColumn::MatchSequenceNumber.as_ref())],
            vec![col(MatchMetadataColumn::Classifier.as_ref())],
            vec![col(MatchMetadataColumn::Excluded.as_ref())],
            vec![col(classifier_bits_col_name("A"))],
            vec![col(MatchMetadataColumn::MatchNumber.as_ref()) + lit(1_i64)],
            vec![
                col("k"),
                col(MatchMetadataColumn::MatchSequenceNumber.as_ref()),
                col(MatchMetadataColumn::MatchNumber.as_ref()),
            ],
        ] {
            assert!(
                window_references_semantic_metadata(&make_window(semantic.clone())),
                "{semantic:?}"
            );
        }
    }

    #[test]
    fn sequence_ordering_is_exempt_only_when_sole_internal_key() {
        let seq_asc = SortExpr::new(
            col(MatchMetadataColumn::MatchSequenceNumber.as_ref()),
            true,
            false,
        );
        let seq_desc = SortExpr::new(
            col(MatchMetadataColumn::MatchSequenceNumber.as_ref()),
            false,
            false,
        );
        let x_desc = SortExpr::new(col("x"), false, true);

        let make_first_agg = |arg: Expr, order_by: Vec<SortExpr>| AggregateFunction {
            func: datafusion::functions_aggregate::first_last::first_value_udaf(),
            params: AggregateFunctionParams {
                args: vec![arg],
                distinct: false,
                filter: None,
                order_by,
                null_treatment: None,
            },
        };
        let make_first_window = |arg: Expr, order_by: Vec<SortExpr>| {
            let mut window = WindowFunction::new(
                WindowFunctionDefinition::AggregateUDF(
                    datafusion::functions_aggregate::first_last::first_value_udaf(),
                ),
                vec![arg],
            );
            window.params.order_by = order_by;
            window
        };
        let classifier = col(MatchMetadataColumn::Classifier.as_ref());

        // Sole synthetic sequence ordering stays internal and managed.
        let sole_internal = vec![seq_asc.clone()];
        assert!(is_sole_internal_sequence_ordering(&sole_internal));
        assert!(!aggregate_references_semantic_metadata(&make_first_agg(
            col("x"),
            sole_internal.clone(),
        )));
        assert!(!window_references_semantic_metadata(&make_first_window(
            col("x"),
            sole_internal.clone(),
        )));
        assert!(is_managed_classifier_navigation_aggregate(&make_first_agg(
            classifier.clone(),
            sole_internal.clone(),
        )));
        assert!(is_managed_classifier_navigation_window(&make_first_window(
            classifier.clone(),
            sole_internal,
        )));

        // Plain data ordering stays managed as well.
        let data_only = vec![x_desc.clone()];
        assert!(!is_sole_internal_sequence_ordering(&data_only));
        assert!(!aggregate_references_semantic_metadata(&make_first_agg(
            col("x"),
            data_only.clone(),
        )));
        assert!(!window_references_semantic_metadata(&make_first_window(
            col("x"),
            data_only.clone(),
        )));
        assert!(is_managed_classifier_navigation_aggregate(&make_first_agg(
            classifier.clone(),
            data_only.clone(),
        )));
        assert!(is_managed_classifier_navigation_window(&make_first_window(
            classifier.clone(),
            data_only,
        )));

        // Multi-key and non-canonical MATCH_SEQUENCE_NUMBER() orderings are
        // semantic metadata and must be rejected on every path.
        for semantic_order in [
            vec![seq_asc.clone(), x_desc.clone()],
            vec![x_desc, seq_asc.clone()],
            vec![seq_asc.clone(), seq_asc],
            vec![seq_desc],
        ] {
            assert!(
                !is_sole_internal_sequence_ordering(&semantic_order),
                "{semantic_order:?}"
            );
            for argument in [col("x"), classifier.clone()] {
                assert!(
                    aggregate_references_semantic_metadata(&make_first_agg(
                        argument.clone(),
                        semantic_order.clone(),
                    )),
                    "{semantic_order:?}"
                );
                assert!(
                    window_references_semantic_metadata(&make_first_window(
                        argument,
                        semantic_order.clone(),
                    )),
                    "{semantic_order:?}"
                );
            }
            assert!(
                !is_managed_classifier_navigation_aggregate(&make_first_agg(
                    classifier.clone(),
                    semantic_order.clone(),
                )),
                "{semantic_order:?}"
            );
            assert!(
                !is_managed_classifier_navigation_window(&make_first_window(
                    classifier.clone(),
                    semantic_order.clone(),
                )),
                "{semantic_order:?}"
            );
        }
    }
}