datafusion-match-recognize 0.55.0

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

//! Single-group accumulator for navigation aggregates.

use std::mem::{size_of, size_of_val};
use std::sync::Arc;

use crate::compat::memory::RecordBatchMemoryCounter;
use datafusion::arrow::array::{
    Array, ArrayRef, AsArray, ListArray, UInt32Array, new_empty_array,
};
use datafusion::arrow::buffer::{OffsetBuffer, ScalarBuffer};
use datafusion::arrow::compute::{concat, take};
use datafusion::arrow::datatypes::{DataType, Field};
use datafusion::arrow::row::Rows;
use datafusion::common::{DataFusionError, Result, ScalarValue};
use datafusion::logical_expr::Accumulator;

use crate::functions::navigation_common::{
    LogicalAnchor, NavigationKind, resolve_navigation_default,
};

use super::helpers::{
    NavigationOrdering, NavigationStateLists, base_state_fields,
    decode_navigation_batch_args, evaluate_navigation_target, last_true_index,
    normalize_state_history_array, state_history_data_type,
};

fn materialize_state_column(
    arrays: &[ArrayRef],
    data_type: &DataType,
    sorted_order: Option<&UInt32Array>,
) -> Result<ArrayRef> {
    let data_type = state_history_data_type(data_type);
    let array = if arrays.is_empty() {
        new_empty_array(&data_type)
    } else {
        let arrays = arrays
            .iter()
            .map(|array| normalize_state_history_array(array, &data_type))
            .collect::<Result<Vec<_>>>()?;
        let refs: Vec<&dyn Array> = arrays.iter().map(|array| array.as_ref()).collect();
        concat(&refs)?
    };
    match sorted_order {
        Some(indices) if !array.is_empty() => Ok(take(array.as_ref(), indices, None)?),
        _ => Ok(array),
    }
}

/// The retained arrays keep all counted buffers alive as history grows.
#[derive(Debug, Default)]
struct RetainedArrayMemory {
    buffers: RecordBatchMemoryCounter,
    wrapper_bytes: usize,
}

impl RetainedArrayMemory {
    fn push(&mut self, arrays: &mut Vec<ArrayRef>, array: ArrayRef) {
        self.buffers.count_array(array.as_ref());
        self.wrapper_bytes +=
            array.get_array_memory_size() - array.get_buffer_memory_size();
        arrays.push(array);
    }
}

/// Accumulator for MATCH_RECOGNIZE navigation aggregates.
///
/// This is DataFusion's single-group aggregate path. Grouped aggregation uses
/// [`NavigationGroupsAccumulator`](super::groups_accumulator::NavigationGroupsAccumulator).
#[derive(Debug)]
pub struct NavigationAccumulator {
    /// Navigation direction selected by the public factory.
    kind: NavigationKind,
    /// Logical anchor (FIRST/LAST + logical offset) for edge or compound shift.
    anchor: LogicalAnchor,
    /// Number of fixed non-ordering arguments expected in `update_batch`.
    fixed_arg_count: usize,
    /// Value arrays retained by reference without copying.
    value_arrays: Vec<ArrayRef>,
    /// Cumulative row count at the end of each array, used for binary search.
    cumulative_rows: Vec<usize>,
    /// Classifier masks that select navigation anchors (shift aggregates only).
    symbol_matched_arrays: Vec<ArrayRef>,
    /// Optional ordering specification and row converter for `ORDER BY` queries.
    ordering: Option<NavigationOrdering>,
    /// Retained ordering arrays per `ORDER BY` key (`ordering_arrays[key][batch]`).
    ordering_arrays: Vec<Vec<ArrayRef>>,
    /// Encoded sort keys for accumulated rows when `ordering` is present.
    ordering_rows: Option<Rows>,
    /// Whether accumulated rows are already in non-decreasing ordering-key order.
    is_sorted: bool,
    array_memory: RetainedArrayMemory,
    /// Total number of accumulated rows.
    total_rows: usize,
    /// Cached index of the last matched row (valid directly when `is_sorted` is true).
    last_matched_idx: Option<usize>,
    /// Number of physical rows to move (0 for logical-offset `FIRST`/`LAST`).
    offset: usize,
    /// Value returned when the target is out of bounds.
    default_value: ScalarValue,
    /// Value data type.
    data_type: DataType,
}

impl NavigationAccumulator {
    #[cfg(test)]
    pub fn new(
        kind: NavigationKind,
        data_type: DataType,
        offset: usize,
        default_value: ScalarValue,
    ) -> Self {
        Self::try_new(kind, data_type, offset, default_value)
            .expect("test navigation default must cast to the result type")
    }

    #[cfg(test)]
    pub(crate) fn try_new(
        kind: NavigationKind,
        data_type: DataType,
        offset: usize,
        default_value: ScalarValue,
    ) -> Result<Self> {
        Self::try_new_with_ordering(kind, data_type, offset, default_value, None)
    }

    #[cfg(test)]
    pub(crate) fn try_new_with_ordering(
        kind: NavigationKind,
        data_type: DataType,
        offset: usize,
        default_value: ScalarValue,
        ordering: Option<NavigationOrdering>,
    ) -> Result<Self> {
        Self::try_new_configured(
            kind,
            data_type,
            LogicalAnchor::Last(0),
            offset,
            default_value,
            super::helpers::NAVIGATION_UDAF_ARG_COUNT,
            ordering,
        )
    }

    pub(crate) fn try_new_configured(
        kind: NavigationKind,
        data_type: DataType,
        anchor: LogicalAnchor,
        offset: usize,
        default_value: ScalarValue,
        fixed_arg_count: usize,
        ordering: Option<NavigationOrdering>,
    ) -> Result<Self> {
        let default_value = resolve_navigation_default(&default_value, &data_type)?;
        let (ordering_arrays, ordering_rows) = match &ordering {
            Some(ordering) => (
                vec![Vec::new(); ordering.num_columns()],
                Some(ordering.empty_rows()),
            ),
            None => (Vec::new(), None),
        };
        Ok(Self {
            kind,
            anchor,
            fixed_arg_count,
            value_arrays: Vec::new(),
            cumulative_rows: Vec::new(),
            symbol_matched_arrays: Vec::new(),
            ordering,
            ordering_arrays,
            ordering_rows,
            is_sorted: true,
            array_memory: RetainedArrayMemory::default(),
            total_rows: 0,
            last_matched_idx: None,
            offset,
            default_value,
            data_type,
        })
    }

    fn append_rows(
        &mut self,
        values: ArrayRef,
        symbol: Option<ArrayRef>,
        orderings: &[ArrayRef],
    ) -> Result<()> {
        if values.is_empty() {
            return Ok(());
        }
        // Without ORDER BY, rows arrive in sequence order; once FIRST(x, k)
        // has observed k + 1 rows, later batches cannot alter the result.
        if self.kind == NavigationKind::First
            && self.ordering.is_none()
            && self.total_rows > self.anchor.offset()
        {
            return Ok(());
        }
        if let Some(ordering) = &self.ordering {
            let rows = self
                .ordering_rows
                .as_mut()
                .expect("ordered navigation accumulator must retain ordering rows");
            let prev_rows = rows.num_rows();
            ordering.append_rows(rows, orderings)?;
            if self.is_sorted {
                let check_start = prev_rows.saturating_sub(1);
                let end = rows.num_rows();
                for idx in check_start..end.saturating_sub(1) {
                    if rows.row(idx) > rows.row(idx + 1) {
                        self.is_sorted = false;
                        break;
                    }
                }
            }
            for (storage, column) in self.ordering_arrays.iter_mut().zip(orderings) {
                self.array_memory.push(storage, Arc::clone(column));
            }
        }
        if let Some(symbol) = symbol {
            if let Some(last_true) = last_true_index(symbol.as_boolean()) {
                self.last_matched_idx = Some(self.total_rows + last_true);
            }
            self.array_memory
                .push(&mut self.symbol_matched_arrays, symbol);
        }
        self.total_rows += values.len();
        self.cumulative_rows.push(self.total_rows);
        self.array_memory.push(&mut self.value_arrays, values);
        Ok(())
    }

    fn locate_row(&self, global_idx: usize) -> Option<(usize, usize)> {
        let array_idx = self
            .cumulative_rows
            .partition_point(|&end| end <= global_idx);
        if array_idx < self.value_arrays.len() {
            let start = array_idx
                .checked_sub(1)
                .map_or(0, |i| self.cumulative_rows[i]);
            Some((array_idx, global_idx - start))
        } else {
            None
        }
    }

    /// Read the value at a global row index.
    fn get_value_at(&self, global_idx: usize) -> Result<ScalarValue> {
        if let Some((array_idx, row_idx)) = self.locate_row(global_idx) {
            let selected = self.value_arrays[array_idx].slice(row_idx, 1);
            let selected = normalize_state_history_array(&selected, &self.data_type)?;
            ScalarValue::try_from_array(&selected, 0)
        } else {
            Ok(self.default_value.clone())
        }
    }

    fn symbol_matched_at(&self, global_idx: usize) -> bool {
        let Some((array_idx, row_idx)) = self.locate_row(global_idx) else {
            return false;
        };
        let symbols = self.symbol_matched_arrays[array_idx].as_boolean();
        symbols.is_valid(row_idx) && symbols.value(row_idx)
    }

    fn find_sorted_symbol_anchor(&self) -> Option<usize> {
        match self.anchor {
            LogicalAnchor::Last(0) => self.last_matched_idx,
            LogicalAnchor::First(offset) => {
                let mut remaining = offset;
                let mut chunk_start = 0usize;
                for chunk in &self.symbol_matched_arrays {
                    let mask = chunk.as_boolean();
                    let trues = mask.true_count();
                    if remaining >= trues {
                        remaining -= trues;
                        chunk_start += mask.len();
                        continue;
                    }
                    for i in 0..mask.len() {
                        if mask.is_valid(i) && mask.value(i) {
                            if remaining == 0 {
                                return Some(chunk_start + i);
                            }
                            remaining -= 1;
                        }
                    }
                }
                None
            }
            LogicalAnchor::Last(offset) => {
                let mut remaining = offset;
                let mut chunk_end = self.total_rows;
                for chunk in self.symbol_matched_arrays.iter().rev() {
                    let mask = chunk.as_boolean();
                    let chunk_start = chunk_end - mask.len();
                    let trues = mask.true_count();
                    if remaining >= trues {
                        remaining -= trues;
                        chunk_end = chunk_start;
                        continue;
                    }
                    for i in (0..mask.len()).rev() {
                        if mask.is_valid(i) && mask.value(i) {
                            if remaining == 0 {
                                return Some(chunk_start + i);
                            }
                            remaining -= 1;
                        }
                    }
                }
                None
            }
        }
    }

    fn sorted_row_indices(&self) -> Vec<usize> {
        let rows = self
            .ordering_rows
            .as_ref()
            .expect("unsorted navigation accumulator must have ordering rows");
        let mut indices: Vec<usize> = (0..self.total_rows).collect();
        indices.sort_by(|&a, &b| rows.row(a).cmp(&rows.row(b)));
        indices
    }
}

impl Accumulator for NavigationAccumulator {
    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
        let batch_args = decode_navigation_batch_args(
            self.kind,
            self.fixed_arg_count,
            &self.data_type,
            values,
            self.ordering.as_ref(),
            self.kind.aggregate_name(),
        )?;
        let value = batch_args.value_array;
        let symbol = batch_args.symbol_mask;
        let orderings = batch_args.ordering_arrays;
        self.append_rows(value, symbol, orderings)
    }

    fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
        if states.is_empty() {
            return Ok(());
        }

        let state_lists = NavigationStateLists::decode(
            states,
            self.kind,
            &self.data_type,
            self.ordering.as_ref(),
            None,
        )?;
        for row in 0..state_lists.values.len() {
            if !state_lists.row_is_present(row)? {
                continue;
            }
            let (values, symbol, orderings) = state_lists.row_slices(row)?;
            self.append_rows(values, symbol, &orderings)?;
        }

        Ok(())
    }

    fn state(&mut self) -> Result<Vec<ScalarValue>> {
        let sorted_order = if self.is_sorted {
            None
        } else {
            i32::try_from(self.total_rows).map_err(|_| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE navigation aggregate state exceeds Arrow List offset capacity"
                        .to_string(),
                )
            })?;
            let indices: Vec<u32> = self
                .sorted_row_indices()
                .into_iter()
                .map(|idx| idx as u32)
                .collect();
            Some(UInt32Array::from(indices))
        };

        let values = materialize_state_column(
            &self.value_arrays,
            &self.data_type,
            sorted_order.as_ref(),
        )?;

        let wrap_list = |arr: ArrayRef, dt: &DataType| -> Result<ScalarValue> {
            let field = Arc::new(Field::new("item", state_history_data_type(dt), true));
            let end = i32::try_from(arr.len()).map_err(|_| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE navigation aggregate state exceeds Arrow List offset capacity"
                        .to_string(),
                )
            })?;
            let offsets = OffsetBuffer::new(ScalarBuffer::from(vec![0, end]));
            let list_arr = ListArray::try_new(field, offsets, arr, None)?;
            Ok(ScalarValue::List(Arc::new(list_arr)))
        };

        let ordering_count = self
            .ordering
            .as_ref()
            .map_or(0, NavigationOrdering::num_columns);
        let mut result =
            Vec::with_capacity(base_state_fields(self.kind) + ordering_count);
        result.push(wrap_list(values, &self.data_type)?);
        if self.kind.is_shift() {
            let symbol_matched = materialize_state_column(
                &self.symbol_matched_arrays,
                &DataType::Boolean,
                sorted_order.as_ref(),
            )?;
            result.push(wrap_list(symbol_matched, &DataType::Boolean)?);
        }
        if let Some(ordering) = &self.ordering {
            for (arrays, data_type) in
                self.ordering_arrays.iter().zip(ordering.data_types())
            {
                let column =
                    materialize_state_column(arrays, data_type, sorted_order.as_ref())?;
                result.push(wrap_list(column, data_type)?);
            }
        }
        Ok(result)
    }

    fn evaluate(&mut self) -> Result<ScalarValue> {
        if self.kind.is_edge() {
            if self.is_sorted {
                return match self.anchor.resolve_unmasked(self.total_rows) {
                    Some(target) => self.get_value_at(target),
                    None => Ok(self.default_value.clone()),
                };
            }
            let sorted = self.sorted_row_indices();
            return match self.anchor.resolve_unmasked(sorted.len()) {
                Some(target) => self.get_value_at(sorted[target]),
                None => Ok(self.default_value.clone()),
            };
        }

        if self.is_sorted {
            let anchor_idx = self.find_sorted_symbol_anchor();
            return evaluate_navigation_target(
                self.kind,
                anchor_idx,
                self.offset,
                self.total_rows,
                &self.default_value,
                |target| self.get_value_at(target),
            );
        }

        let sorted = self.sorted_row_indices();
        let anchor_idx = self
            .anchor
            .resolve_masked(sorted.len(), |i| self.symbol_matched_at(sorted[i]));
        evaluate_navigation_target(
            self.kind,
            anchor_idx,
            self.offset,
            sorted.len(),
            &self.default_value,
            |target| self.get_value_at(sorted[target]),
        )
    }

    fn size(&self) -> usize {
        // Self includes vector headers; backing storage can have spare capacity.
        let ordering_array_vec_bytes = self.ordering_arrays.capacity()
            * size_of::<Vec<ArrayRef>>()
            + self
                .ordering_arrays
                .iter()
                .map(|arrays| arrays.capacity() * size_of::<ArrayRef>())
                .sum::<usize>();
        let vector_storage_size = (self.value_arrays.capacity()
            + self.symbol_matched_arrays.capacity())
            * size_of::<ArrayRef>()
            + self.cumulative_rows.capacity() * size_of::<usize>()
            + ordering_array_vec_bytes;
        let ordering_meta_size = self
            .ordering
            .as_ref()
            .map_or(0, NavigationOrdering::heap_size);
        let ordering_rows_size = self
            .ordering_rows
            .as_ref()
            .map_or(0, |rows| rows.size() - size_of_val(rows));
        size_of_val(self)
            + vector_storage_size
            + self.array_memory.buffers.memory_usage()
            + self.array_memory.wrapper_bytes
            + ordering_meta_size
            + ordering_rows_size
            + (self.default_value.size() - size_of_val(&self.default_value))
            + (self.data_type.size() - size_of_val(&self.data_type))
    }
}

#[cfg(test)]
mod resource_tests {
    use super::*;
    use datafusion::arrow::array::NullArray;

    #[test]
    fn state_rejects_values_too_large_for_list_offsets() {
        let mut accumulator = NavigationAccumulator::new(
            NavigationKind::Prev,
            DataType::Null,
            1,
            ScalarValue::Null,
        );
        accumulator.array_memory.push(
            &mut accumulator.value_arrays,
            Arc::new(NullArray::new(i32::MAX as usize + 1)),
        );

        let error = accumulator
            .state()
            .expect_err("Arrow List state must reject an unrepresentable offset");
        assert!(matches!(
            error,
            DataFusionError::ResourcesExhausted(message)
                if message.contains("Arrow List offset capacity")
        ));
    }
}