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

//! Navigation admission and history ownership on the Lane route.

use super::*;
use crate::core::vm::NavigationSource;

#[test]
fn decimal_first_last_lane_preserves_general_restart_history() {
    use crate::core::vm::{
        NavSlotInfo, NavigationLayout, NavigationLocation, NavigationValueDomain,
    };
    use crate::execution::matching::add_nav_register_at;
    use crate::execution::matching::row_loop::compiled_program::{
        LaneOutcome, build_exact_aggregate_history,
    };
    use crate::execution::matching::row_loop::lane_scan::LaneRejection;
    use crate::planning::ManagedAggregateBackendSet;
    use crate::planning::predicate::VmScalarType;
    use datafusion::arrow::array::Decimal128Array;
    use datafusion::functions_aggregate::first_last::{
        first_value_udaf, last_value_udaf,
    };
    use datafusion::logical_expr::{col, lit};

    let build = |pattern: Pattern| {
        let normalized_pattern = NormalizedPattern::Ast(pattern.clone());
        let compiled = compile_test_pattern(pattern, &["A", "B", "C", "D"]);
        let symbol_id = |index| SymbolId::try_new(index, compiled.num_symbols()).unwrap();

        let base = make_batch(
            &[1, 2, 3, 4, 5],
            &[
                ("A", vec![true, true, true, false, false]),
                ("B", vec![false, false, false, true, false]),
                ("C", vec![false, false, false, true, false]),
            ],
        );
        let mut fields = base.schema().fields().to_vec();
        fields.push(Arc::new(Field::new(
            "amount",
            DataType::Decimal128(10, 2),
            true,
        )));
        let mut columns = base.columns().to_vec();
        columns.push(Arc::new(
            Decimal128Array::from(vec![Some(1_000), None, Some(3_000), None, None])
                .with_precision_and_scale(10, 2)
                .unwrap(),
        ));
        let base = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap();

        let (batch, qualified_count, _) =
            add_count_register_at(base, Some(symbol_id(1)), 0, 4);
        let (batch, unqualified_count, _) = add_count_register_at(batch, None, 1, 4);
        let (batch, first_amount, _) = add_nav_register_at(
            batch,
            "amount",
            first_value_udaf(),
            Some(symbol_id(1)),
            2,
            4,
        );
        let (batch, last_amount, _) = add_nav_register_at(
            batch,
            "amount",
            last_value_udaf(),
            Some(symbol_id(1)),
            3,
            4,
        );

        let decimal_scalar = VmScalarType::Decimal128 {
            precision: 10,
            scale: 2,
        };
        let predicate = predicate_test_helper::compile(
            col("__mr_managed_agg_2")
                .lt_eq(col("__mr_managed_agg_3"))
                .and(
                    (col("__mr_managed_agg_0") + lit(2_i64))
                        .eq(col("__mr_managed_agg_1")),
                ),
            &[
                VmScalarType::Int64,
                VmScalarType::Int64,
                decimal_scalar,
                decimal_scalar,
            ],
            vec![],
        );
        let true_expr = Arc::new(datafusion_physical_expr::expressions::Literal::new(
            datafusion::scalar::ScalarValue::Boolean(Some(true)),
        )) as Arc<dyn PhysicalExpr>;
        let mut programs = vec![test_user_symbol_program(
            symbol_id(1),
            SymbolEvalMode::Static,
            None,
            None,
            vec![
                RegisterWriter::Count {
                    aggregate: 0,
                    input: None,
                },
                RegisterWriter::Count {
                    aggregate: 1,
                    input: None,
                },
            ],
            None,
        )];
        programs.extend((2..=3).map(|index| {
            test_user_symbol_program(
                symbol_id(index),
                SymbolEvalMode::Static,
                None,
                None,
                vec![RegisterWriter::Count {
                    aggregate: 1,
                    input: None,
                }],
                None,
            )
        }));
        programs.push(test_user_symbol_program(
            symbol_id(4),
            SymbolEvalMode::Incremental,
            Some(true_expr),
            None,
            vec![RegisterWriter::Count {
                aggregate: 1,
                input: None,
            }],
            Some(predicate),
        ));
        let navigation_layout = NavigationLayout {
            num_nav_slots: 4,
            first_slots: vec![NavSlotInfo {
                symbol_idx: Some(0),
                nav_slot: 0,
                value_idx: 0,
                domain: NavigationValueDomain::Decimal128,
            }],
            last_slots: vec![NavSlotInfo {
                symbol_idx: Some(0),
                nav_slot: 2,
                value_idx: 0,
                domain: NavigationValueDomain::Decimal128,
            }],
            ..Default::default()
        };
        let register_layout = RegisterLayout::builder(
            2,
            vec![
                AggregateLayout {
                    slot: Some(SlotInfo::int64(0)),
                    value_source: AggregateValueSource::Register { slot: 0 },
                    ..Default::default()
                },
                AggregateLayout {
                    slot: Some(SlotInfo::int64(1)),
                    value_source: AggregateValueSource::Register { slot: 1 },
                    ..Default::default()
                },
                AggregateLayout {
                    value_source: AggregateValueSource::Navigation(NavigationSource {
                        location: NavigationLocation::First(0),
                        domain: NavigationValueDomain::Decimal128,
                        default_value: None,
                    }),
                    ..Default::default()
                },
                AggregateLayout {
                    value_source: AggregateValueSource::Navigation(NavigationSource {
                        location: NavigationLocation::Last(2),
                        domain: NavigationValueDomain::Decimal128,
                        default_value: None,
                    }),
                    ..Default::default()
                },
            ],
        )
        .navigation_inputs(vec![], vec!["amount".to_string()], Some(navigation_layout))
        .try_build()
        .unwrap();
        let symbol_programs =
            SymbolProgramTable::try_new(programs, register_layout).unwrap();
        let rows_per_match = RowsPerMatch::AllRows(EmptyMatchesMode::Show);
        let output = metadata_output(&batch, compiled.as_ref(), rows_per_match.clone());
        let row_count = batch.num_rows();
        let mut config = deterministic_test_config();
        config.diagnostics.disable_pattern_optimizer = true;
        config.diagnostics.disable_compact_paths = true;
        let driver = CollectionTestDriver::try_new(
            batch,
            normalized_pattern,
            compiled,
            &config,
            row_count * row_count,
            output,
            move |input| {
                input.symbols.symbol_programs = symbol_programs;
                input.aggregate_programs = vec![
                    qualified_count,
                    unqualified_count,
                    first_amount,
                    last_amount,
                ];
                input.after_match_skip = ResolvedAfterMatchSkip::ToNextRow;
                input.set_rows_per_match(rows_per_match);
            },
        )
        .unwrap();
        let prepared = driver.matcher.program.prepared.as_ref();
        assert!(prepared.has_symbol_qualified_aggregates);
        assert!(prepared.has_unqualified_aggregates);
        assert_eq!(prepared.aggregate_hot_tables.factories.len(), 4);
        assert_eq!(
            driver.matcher.aggregate_backend_set(),
            ManagedAggregateBackendSet::RegistersOnly
        );
        let exact = build_exact_aggregate_history(prepared, prepared.automaton.as_ref());
        assert!(exact.empty_position_tracking().is_some());
        assert!(exact.empty_labeled_tracking().is_some());
        driver
    };

    let accepted_pattern = || {
        concat(vec![
            rep(sym("A"), RepetitionQuantifier::OneOrMore),
            alt(vec![sym("B"), sym("C")]),
            sym("D"),
        ])
    };
    let run = |force_generic| {
        let mut driver = build(accepted_pattern());
        let base = driver.matcher.program.base_variant();
        assert!(matches!(base.lane_outcome(), LaneOutcome::Enabled(_)));
        // Lane stores packed values, while a later capacity miss must still
        // be able to instantiate General's exact aggregate history.
        assert!(base.empty_position_tracking().is_some());
        assert!(base.empty_labeled_tracking().is_some());
        assert!(base.requires_position_offset());
        driver.matcher.force_generic_scan_for_test(force_generic);
        driver.enable_matcher_metrics();
        let yields = finish_local_collection(&mut driver, 1, 10_000);
        driver.flush_output(5, true, None).unwrap();
        (
            driver.concat_output(),
            yields,
            driver.metrics.route_scan_specialized.value(),
            driver.metrics.route_scan_generic.value(),
        )
    };

    let lane = run(false);
    let generic = run(true);
    assert_eq!(lane.0, generic.0);
    assert!(lane.1 > 0 && generic.1 > 0);
    assert!(lane.2 > 0 && lane.3 == 0);
    assert!(generic.2 == 0 && generic.3 > 0);
    assert_match_rows(
        &lane.0,
        &[1, 2, 3, 4, 5, 3, 4, 5],
        &[1, 1, 1, 1, 1, 2, 2, 2],
        &[1, 2, 3, 4, 5, 1, 2, 3],
        None,
    );
    assert_eq!(
        output_array::<StringArray>(&lane.0, "__mr_classifier"),
        &StringArray::from(vec!["A", "A", "A", "B", "D", "A", "B", "D"])
    );
    let rejected_pattern = concat(vec![
        rep(
            alt(vec![sym("A"), sym("B")]),
            RepetitionQuantifier::OneOrMore,
        ),
        sym("D"),
    ]);
    let rejected = build(rejected_pattern);
    let rejected_variant = rejected.matcher.program.base_variant();
    assert_eq!(
        rejected_variant.lane_outcome().rejection(),
        Some(LaneRejection::Graph)
    );
    assert!(rejected_variant.empty_position_tracking().is_some());
    assert!(rejected_variant.empty_labeled_tracking().is_some());
}

#[test]
fn converging_lanes_keep_distinct_last_values_without_register_slots() {
    use crate::core::vm::{
        NavSlotInfo, NavigationLayout, NavigationLocation, NavigationValueDomain,
    };
    use crate::execution::matching::add_nav_register_at;
    use datafusion::functions_aggregate::first_last::last_value_udaf;
    use datafusion::logical_expr::{col, lit};

    // AAB and ABB reach the B loop from the same start with LAST(A.id)
    // equal to 2 and 1 respectively. Only the second history can consume C.
    let batch = make_batch(
        &[1, 2, 3, 4, 5],
        &[
            ("A", vec![true, true, false, false, false]),
            ("B", vec![false, true, true, true, false]),
        ],
    );
    let pattern = concat(vec![
        rep(sym("A"), RepetitionQuantifier::OneOrMore),
        rep(sym("B"), RepetitionQuantifier::OneOrMore),
        sym("C"),
    ]);
    let compiled = compile_test_pattern(pattern.clone(), &["A", "B", "C"]);
    let id = |index| SymbolId::try_new(index, compiled.num_symbols()).unwrap();
    let (batch, last_id, _) =
        add_nav_register_at(batch, "id", last_value_udaf(), Some(id(1)), 0, 1);
    let predicate = predicate_test_helper::compile(
        col("__mr_managed_agg_0").eq(lit(1_u32)),
        &[VmScalarType::UInt32],
        vec![],
    );
    let layout = RegisterLayout::builder(
        0,
        vec![AggregateLayout {
            value_source: AggregateValueSource::Navigation(NavigationSource {
                location: NavigationLocation::Last(0),
                domain: NavigationValueDomain::Primitive,
                default_value: None,
            }),
            ..Default::default()
        }],
    )
    .navigation_inputs(
        vec!["id".into()],
        vec![],
        Some(NavigationLayout {
            num_nav_slots: 1,
            last_slots: vec![NavSlotInfo {
                symbol_idx: Some(0),
                nav_slot: 0,
                value_idx: 0,
                domain: NavigationValueDomain::Primitive,
            }],
            ..Default::default()
        }),
    )
    .try_build()
    .unwrap();
    let programs = SymbolProgramTable::try_new(
        vec![
            test_user_symbol_program(
                id(1),
                SymbolEvalMode::Static,
                None,
                None,
                vec![],
                None,
            ),
            test_user_symbol_program(
                id(2),
                SymbolEvalMode::Static,
                None,
                None,
                vec![],
                None,
            ),
            test_user_symbol_program(
                id(3),
                SymbolEvalMode::Incremental,
                Some(Arc::new(
                    datafusion_physical_expr::expressions::Literal::new(
                        datafusion::scalar::ScalarValue::Boolean(Some(true)),
                    ),
                )),
                None,
                vec![],
                Some(predicate),
            ),
        ],
        layout,
    )
    .unwrap();
    let rows = RowsPerMatch::AllRows(EmptyMatchesMode::Show);
    let output = metadata_output(&batch, &compiled, rows.clone());
    let mut driver = CollectionTestDriver::try_new(
        batch,
        NormalizedPattern::Ast(pattern),
        compiled,
        &deterministic_test_config(),
        16,
        output,
        |input| {
            input.symbols.symbol_programs = programs;
            input.aggregate_programs = vec![last_id];
            input.set_rows_per_match(rows);
        },
    )
    .unwrap();
    assert!(driver.matcher.has_managed_aggregates());
    driver.enable_matcher_metrics();
    finish_local_collection(&mut driver, 1, 1000);
    driver.flush_output(5, true, None).unwrap();
    assert!(driver.metrics.route_scan_specialized.value() > 0);
    assert_eq!(driver.metrics.route_scan_generic.value(), 0);
    assert_eq!(
        output_array::<StringArray>(&driver.concat_output(), "__mr_classifier"),
        &StringArray::from(vec!["A", "B", "B", "B", "C"])
    );
}