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

//! Updates managed aggregates assigned to DataFusion accumulators.
//!
//! Physical planning has already chosen this backend. The row loop supplies the
//! current row and argument provider. This module requests arguments for the
//! transition's contributing aggregates, then updates and reads the accumulators.

use crate::core::AggregateId;
use crate::core::AggregateValue;
use crate::core::SymbolId;
use crate::execution::common::progress::CoarseWorkCounter;
use crate::execution::matching::row_loop::provider::ValueProvider;
use crate::planning::AccumulatorInputMode;
use datafusion::arrow::array::ArrayRef;
use datafusion::arrow::array::BooleanArray;
use datafusion::arrow::datatypes::DataType;
use datafusion::logical_expr::Accumulator;
use datafusion_common::Result;
use datafusion_common::ScalarValue;
use datafusion_common::internal_err;
use std::sync::Arc;
use std::sync::OnceLock;

/// Immutable update descriptors shared by the physical program's matchers.
///
/// Accumulators and result buffers belong to the candidate and row loop.
#[derive(Clone)]
pub struct ManagedAccumulatorEvaluator {
    aggregators: Arc<[ManagedAggregator]>,
}

impl ManagedAccumulatorEvaluator {
    pub fn new<'a>(
        aggregate_programs: impl ExactSizeIterator<
            Item = &'a crate::execution::matching::program::contracts::AggregateProgram,
        >,
    ) -> Self {
        let mut aggregators = Vec::with_capacity(aggregate_programs.len());
        for program in aggregate_programs {
            let aggregate_id = program.id();
            aggregators.push(ManagedAggregator {
                aggregate_id,
                symbol_id: program.symbol_id(),
                update_mode: program.accumulator_input_mode(),
                output_type: program.output_type().clone(),
            });
        }

        Self {
            aggregators: aggregators.into(),
        }
    }
}

impl ManagedAccumulatorEvaluator {
    /// Update every local managed accumulator for one transition.
    #[allow(clippy::too_many_arguments)]
    pub fn update_aggregates<Report>(
        &self,
        provider: &mut ValueProvider<'_>,
        accumulators: &mut [Option<Box<dyn Accumulator>>],
        factories: &[Arc<datafusion_physical_expr::aggregate::AggregateFunctionExpr>],
        symbol_matched: SymbolId,
        out_results: &mut Vec<ScalarValue>,
        out_primitive_results: &mut Vec<AggregateValue>,
        report_completed_work: &mut Report,
    ) -> Result<()>
    where
        Report: FnMut(usize) -> Result<()>,
    {
        out_results.clear();
        out_primitive_results.clear();

        let mut work = CoarseWorkCounter::new();
        let update_result = (|| {
            for agg in self.aggregators.iter() {
                let accumulator_idx = agg.aggregate_id.index();
                let Some(slot) = accumulators.get_mut(accumulator_idx) else {
                    return internal_err!(
                        "MATCH_RECOGNIZE managed accumulator slot is missing for aggregate {} at index {}",
                        agg.aggregate_id,
                        accumulator_idx
                    );
                };
                let acc = match slot {
                    Some(acc) => acc,
                    None => {
                        let Some(factory) = factories.get(accumulator_idx) else {
                            return internal_err!(
                                "MATCH_RECOGNIZE managed accumulator factory is missing for aggregate {} at index {}",
                                agg.aggregate_id,
                                accumulator_idx
                            );
                        };
                        let accumulator = factory.create_accumulator();
                        let accounting = work.complete_one(report_completed_work);
                        let accumulator = accumulator?;
                        accounting?;
                        slot.insert(accumulator)
                    }
                };

                if should_update_for_symbol(agg.symbol_id, symbol_matched) {
                    let values = provider.evaluate_args(
                        agg.aggregate_id,
                        &mut work,
                        report_completed_work,
                    )?;
                    let update_result = match agg.update_mode {
                        AccumulatorInputMode::Batch => acc.update_batch(values),
                        AccumulatorInputMode::PreviousValue => {
                            let values = prev_accumulator_values(values)?;
                            acc.update_batch(values.as_ref())
                        }
                    };
                    let accounting = work.complete_one(report_completed_work);
                    update_result?;
                    accounting?;
                }

                let evaluate_result = acc.evaluate();
                let accounting = work.complete_one(report_completed_work);
                let val = evaluate_result?;
                accounting?;
                append_accumulator_result(
                    val,
                    &agg.output_type,
                    out_results,
                    out_primitive_results,
                )?;
            }
            Ok(())
        })();
        work.finish_result(update_result, report_completed_work)?;
        debug_assert!(
            out_primitive_results.is_empty()
                || out_primitive_results.len() == out_results.len(),
            "managed accumulator primitive results must be empty or complete"
        );
        Ok(())
    }
}

#[cfg(test)]
pub(crate) mod lazy_tests;

#[cfg(test)]
mod tests {
    use super::{ManagedAccumulatorEvaluator, ManagedAggregator};
    use crate::config::CancellationPolicy;
    use crate::core::{AggregateId, AggregateValue, SymbolId};
    use crate::execution::matching::row_loop::provider::ValueProvider;
    use crate::execution::matching::row_loop::state::WorkGovernor;
    use crate::planning::AccumulatorInputMode;
    use datafusion::arrow::array::{ArrayRef, Int64Array};
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion::arrow::record_batch::RecordBatch;
    use datafusion::logical_expr::Accumulator;
    use datafusion::scalar::ScalarValue;
    use datafusion_common::{DataFusionError, Result};
    use std::mem::size_of_val;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

    const MANAGED_WIDTH: usize = 2 * 64 + 1;

    #[derive(Debug)]
    struct ProbeAccumulator {
        calls: Arc<AtomicUsize>,
        abort: Arc<AtomicBool>,
        fail_call: Option<usize>,
        value: i64,
    }

    impl ProbeAccumulator {
        fn record_call(&self) -> Result<()> {
            let call = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
            if self.fail_call == Some(call) {
                self.abort.store(true, Ordering::SeqCst);
                return Err(DataFusionError::Execution(
                    "primary accumulator failure".into(),
                ));
            }
            Ok(())
        }
    }

    impl Accumulator for ProbeAccumulator {
        fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {
            self.record_call()?;
            self.value += 1;
            Ok(())
        }

        fn evaluate(&mut self) -> Result<ScalarValue> {
            self.record_call()?;
            Ok(ScalarValue::Int64(Some(self.value)))
        }

        fn size(&self) -> usize {
            size_of_val(self)
        }

        fn state(&mut self) -> Result<Vec<ScalarValue>> {
            Ok(vec![ScalarValue::Int64(Some(self.value))])
        }

        fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {
            Ok(())
        }
    }

    fn evaluator() -> ManagedAccumulatorEvaluator {
        let symbol_id = SymbolId::try_new(1, 2).unwrap();
        ManagedAccumulatorEvaluator {
            aggregators: (0..MANAGED_WIDTH)
                .map(|index| ManagedAggregator {
                    aggregate_id: AggregateId::try_new(index, MANAGED_WIDTH).unwrap(),
                    symbol_id: Some(symbol_id),
                    update_mode: AccumulatorInputMode::Batch,
                    output_type: DataType::Int64,
                })
                .collect(),
        }
    }

    fn accumulators(
        calls: &Arc<AtomicUsize>,
        abort: &Arc<AtomicBool>,
        fail_call: Option<usize>,
    ) -> Vec<Option<Box<dyn Accumulator>>> {
        (0..MANAGED_WIDTH)
            .map(|_| {
                Some(Box::new(ProbeAccumulator {
                    calls: Arc::clone(calls),
                    abort: Arc::clone(abort),
                    fail_call,
                    value: 0,
                }) as Box<dyn Accumulator>)
            })
            .collect()
    }

    fn provider_case() -> (RecordBatch, Vec<Vec<ArrayRef>>) {
        let schema = Arc::new(Schema::new(vec![Field::new(
            "value",
            DataType::Int64,
            false,
        )]));
        let value = Arc::new(Int64Array::from(vec![1])) as ArrayRef;
        let batch = RecordBatch::try_new(schema, vec![Arc::clone(&value)]).unwrap();
        let arguments = (0..MANAGED_WIDTH)
            .map(|_| vec![Arc::clone(&value)])
            .collect();
        (batch, arguments)
    }

    #[test]
    fn many_managed_accumulators_cancel_at_opaque_call_boundary_and_retry() {
        let evaluator = evaluator();
        let (_batch, arguments) = provider_case();
        let mut provider = ValueProvider::Prepared(&arguments);
        for (fail_call, expected_error) in [
            (None, "cancelled"),
            (Some(64), "primary accumulator failure"),
        ] {
            let calls = Arc::new(AtomicUsize::new(0));
            let abort = Arc::new(AtomicBool::new(fail_call.is_none()));
            let mut disposable = accumulators(&calls, &abort, fail_call);
            let mut results = Vec::new();
            let mut primitive = Vec::<AggregateValue>::new();
            let mut governor = WorkGovernor::default();
            governor
                .bind_cancellation_policy(
                    CancellationPolicy::try_from_configured(64, 0).unwrap(),
                )
                .unwrap();
            let mut cancelled_reports = Vec::new();
            let error = evaluator
                .update_aggregates(
                    &mut provider,
                    &mut disposable,
                    &[],
                    SymbolId::try_new(1, 2).unwrap(),
                    &mut results,
                    &mut primitive,
                    &mut |units| {
                        cancelled_reports.push(units);
                        governor.record_completed(units, || abort.load(Ordering::SeqCst))
                    },
                )
                .expect_err("the first 64 opaque calls must observe cancellation");
            assert!(error.to_string().contains(expected_error), "{error}");
            if fail_call.is_some() {
                assert!(!error.to_string().contains("cancelled"));
            }
            assert_eq!(cancelled_reports, [64]);
            assert_eq!(calls.load(Ordering::SeqCst), 64);
            assert_eq!(results.len(), 31);

            assert_eq!(governor.progress_epoch_for_observation(), 64);
            if fail_call.is_some() {
                continue;
            }
            drop(disposable);
            abort.store(false, Ordering::SeqCst);
            let mut retry = accumulators(&calls, &abort, None);
            let mut retry_reports = Vec::new();
            evaluator
                .update_aggregates(
                    &mut provider,
                    &mut retry,
                    &[],
                    SymbolId::try_new(1, 2).unwrap(),
                    &mut results,
                    &mut primitive,
                    &mut |units| {
                        retry_reports.push(units);
                        governor.record_completed(units, || abort.load(Ordering::SeqCst))
                    },
                )
                .unwrap();
            assert_eq!(retry_reports, [64, 64, 64, 64, 2]);
            assert_eq!(calls.load(Ordering::SeqCst), 64 + MANAGED_WIDTH * 2);
            assert_eq!(
                governor.progress_epoch_for_observation(),
                (64 + MANAGED_WIDTH * 2) as u64
            );
            assert_eq!(results, vec![ScalarValue::Int64(Some(1)); MANAGED_WIDTH]);

            assert_eq!(primitive, vec![AggregateValue::Int64(1); MANAGED_WIDTH]);
        }
    }
}

// Decide which aggregate updates apply to the transition.

/// Determines if an accumulator should be updated for the current row.
///
/// Returns `true` if:
/// - The aggregate has no symbol qualifier (unqualified aggregates update on every row)
/// - The aggregate's bound symbol ID matches the current transition symbol
#[inline]
fn should_update_for_symbol(symbol: Option<SymbolId>, current_matched: SymbolId) -> bool {
    symbol.is_none_or(|scope| scope == current_matched)
}

fn primitive_accumulator_result(value: &ScalarValue) -> Option<AggregateValue> {
    if value.is_null() {
        return Some(AggregateValue::Null);
    }
    AggregateValue::from_scalar(value)
}

fn append_accumulator_result(
    value: ScalarValue,
    output_type: &DataType,
    out_results: &mut Vec<ScalarValue>,
    out_primitive_results: &mut Vec<AggregateValue>,
) -> Result<()> {
    // Direct predicates and state equivalence must see the same declared type
    // as physical-expression evaluation, including decimal scale and typed NULLs.
    let value = if value.data_type() == *output_type {
        value
    } else {
        value.cast_to(output_type)?
    };
    // Scalar results are the complete semantic representation and remain
    // available to physical-expression fallback. The primitive snapshot is an
    // optimization used by direct predicates and state equivalence; publish it
    // only while every preceding result and this result are representable.
    if out_primitive_results.len() == out_results.len() {
        if let Some(primitive) = primitive_accumulator_result(&value) {
            out_primitive_results.push(primitive);
        } else {
            out_primitive_results.clear();
        }
    }
    out_results.push(value);
    Ok(())
}

/// Updates managed aggregates through DataFusion's generic `Accumulator` API.
///
/// For navigation functions, the mode controls how internal mask arguments are
/// presented to the accumulator. Symbol filtering is already handled by
/// `should_update_for_symbol`, so `FIRST` and `LAST` can use only their value
/// argument. `PREV` still needs its offset and default; it receives those plus
/// synthetic `TRUE` masks for the already-filtered single row. Source-planned
/// physical offsets arrive as `PREV(0)` over a prepared LAG column.
pub(super) struct ManagedAggregator {
    pub(super) aggregate_id: AggregateId,
    pub(super) symbol_id: Option<SymbolId>,
    pub(super) update_mode: AccumulatorInputMode,
    pub(super) output_type: DataType,
}

#[derive(Debug)]
enum PrevAccumulatorValues {
    Standard([ArrayRef; 5]),
    Extended(Vec<ArrayRef>),
}

impl AsRef<[ArrayRef]> for PrevAccumulatorValues {
    fn as_ref(&self) -> &[ArrayRef] {
        match self {
            Self::Standard(values) => values,
            Self::Extended(values) => values,
        }
    }
}

fn prev_accumulator_values(values: &[ArrayRef]) -> Result<PrevAccumulatorValues> {
    if values.len() < 3 {
        return internal_err!(
            "PREV managed aggregate expected value, offset, and default arguments"
        );
    }

    if values.iter().any(|array| array.len() != 1) {
        return internal_err!(
            "PREV managed aggregate expected aligned singleton arguments"
        );
    }
    static TRUE_SINGLETON: OnceLock<ArrayRef> = OnceLock::new();
    let matched = TRUE_SINGLETON
        .get_or_init(|| Arc::new(BooleanArray::from(vec![true])) as ArrayRef);
    let base = [
        Arc::clone(&values[0]),
        Arc::clone(&values[1]),
        Arc::clone(&values[2]),
        Arc::clone(matched),
        Arc::clone(matched),
    ];
    if values.len() == 3 {
        return Ok(PrevAccumulatorValues::Standard(base));
    }
    let mut forwarded = Vec::with_capacity(values.len() + 2);
    forwarded.extend(base);
    forwarded.extend(values[3..].iter().cloned());
    Ok(PrevAccumulatorValues::Extended(forwarded))
}

#[cfg(test)]
mod update_tests {
    use super::{append_accumulator_result, prev_accumulator_values};
    use crate::core::AggregateValue;
    use datafusion::arrow::array::{ArrayRef, Int64Array};
    use datafusion::arrow::datatypes::DataType;
    use datafusion::scalar::ScalarValue;
    use std::sync::Arc;

    #[test]
    fn accumulator_snapshots_use_the_declared_output_type() {
        for (value, output_type) in [
            (ScalarValue::Int64(Some(7)), DataType::Float64),
            (ScalarValue::Int64(None), DataType::Decimal128(12, 2)),
            (
                ScalarValue::Decimal128(Some(123), 10, 2),
                DataType::Decimal128(12, 3),
            ),
            (ScalarValue::Utf8(Some("7".into())), DataType::Int64),
            (ScalarValue::Int64(Some(7)), DataType::Utf8),
        ] {
            let expected = value.cast_to(&output_type).unwrap();
            let mut results = Vec::new();
            let mut primitive = Vec::new();
            append_accumulator_result(value, &output_type, &mut results, &mut primitive)
                .unwrap();
            assert_eq!(results.as_slice(), std::slice::from_ref(&expected));
            assert_eq!(
                primitive,
                super::primitive_accumulator_result(&expected)
                    .into_iter()
                    .collect::<Vec<_>>()
            );
        }
    }

    #[test]
    fn failed_output_cast_does_not_publish_either_snapshot() {
        let mut results = vec![ScalarValue::Int64(Some(1))];
        let mut primitive = vec![AggregateValue::Int64(1)];
        assert!(
            append_accumulator_result(
                ScalarValue::Utf8(Some("invalid".into())),
                &DataType::Int64,
                &mut results,
                &mut primitive,
            )
            .is_err()
        );
        assert_eq!(results, [ScalarValue::Int64(Some(1))]);
        assert_eq!(primitive, [AggregateValue::Int64(1)]);
    }

    #[test]
    fn prev_forwards_value_offset_default_and_matched_masks() {
        let values =
            [10, 1, 0].map(|value| Arc::new(Int64Array::from(vec![value])) as ArrayRef);
        let forwarded = prev_accumulator_values(&values).unwrap();
        let forwarded = forwarded.as_ref();
        for (index, expected) in [10, 1, 0].into_iter().enumerate() {
            assert_eq!(
                ScalarValue::try_from_array(&forwarded[index], 0).unwrap(),
                ScalarValue::Int64(Some(expected))
            );
        }
        for mask in &forwarded[3..] {
            assert_eq!(
                ScalarValue::try_from_array(mask, 0).unwrap(),
                ScalarValue::Boolean(Some(true))
            );
        }

        let compound = [10, 0, -1, 1, 2]
            .map(|value| Arc::new(Int64Array::from(vec![value])) as ArrayRef);
        let forwarded_compound = prev_accumulator_values(&compound).unwrap();
        let forwarded_compound = forwarded_compound.as_ref();
        assert_eq!(forwarded_compound.len(), 7);
        assert_eq!(
            ScalarValue::try_from_array(&forwarded_compound[5], 0).unwrap(),
            ScalarValue::Int64(Some(1))
        );
        assert_eq!(
            ScalarValue::try_from_array(&forwarded_compound[6], 0).unwrap(),
            ScalarValue::Int64(Some(2))
        );
    }

    #[test]
    fn prev_rejects_missing_non_singleton_and_misaligned_arguments() {
        for (lengths, message) in [
            (&[1, 1][..], "value, offset, and default"),
            (&[2, 2, 2][..], "aligned singleton"),
            (&[1, 2, 1][..], "aligned singleton"),
        ] {
            let values = lengths
                .iter()
                .map(|length| Arc::new(Int64Array::from(vec![1; *length])) as ArrayRef)
                .collect::<Vec<_>>();
            let error = prev_accumulator_values(&values).unwrap_err().to_string();
            assert!(error.contains(message), "{lengths:?}: {error}");
        }
    }

    #[test]
    fn accumulator_results_preserve_scalars_and_only_complete_primitive_snapshots() {
        let values = [
            ScalarValue::Int64(Some(1)),
            ScalarValue::Utf8(None),
            ScalarValue::Utf8(Some("value".into())),
            ScalarValue::Int64(Some(3)),
        ];
        let mut results = Vec::new();
        let mut primitive_results = Vec::new();
        for (index, expected) in [
            &[AggregateValue::Int64(1)][..],
            &[AggregateValue::Int64(1), AggregateValue::Null][..],
            &[],
            &[],
        ]
        .into_iter()
        .enumerate()
        {
            append_accumulator_result(
                values[index].clone(),
                &values[index].data_type(),
                &mut results,
                &mut primitive_results,
            )
            .unwrap();
            assert_eq!(results, values[..=index]);
            assert_eq!(primitive_results, expected);
        }
    }
}