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

use super::{NavigationInput, Neighbor, PACKED_CLASSIFY_CHUNK_ROWS};
use datafusion::arrow::array::{
    Array, ArrayRef, AsArray, BinaryViewArray, BooleanArray, StringViewArray,
};
use datafusion::arrow::buffer::{BooleanBuffer, Buffer, NullBuffer};
use datafusion::arrow::compute::nullif;
use datafusion::arrow::datatypes::DataType;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::Result;
use std::sync::Arc;

const MISSING_WORDS: usize = PACKED_CLASSIFY_CHUNK_ROWS / (u64::BITS as usize);

impl Neighbor {
    /// Mask missing neighbors while sharing the entire view data-buffer table.
    pub(crate) fn mask_array_with_nulls(
        array: &ArrayRef,
        mask: &BooleanArray,
    ) -> Result<ArrayRef> {
        if !matches!(array.data_type(), DataType::Utf8View | DataType::BinaryView)
            || array.len() != mask.len()
        {
            return Ok(nullif(array.as_ref(), mask)?);
        }
        // Like Arrow nullif, a NULL mask entry preserves the source validity.
        let valid = NullBuffer::new(match mask.nulls() {
            Some(nulls) => !&(mask.values() & nulls.inner()),
            None => !mask.values(),
        });
        let nulls = NullBuffer::union(array.nulls(), Some(&valid));
        // Going through ArrayData would copy every Buffer handle, even when
        // this array is a tiny slice of a source with thousands of buffers.
        Ok(match array.data_type() {
            DataType::Utf8View => {
                let view = array.as_string_view();
                Arc::new(StringViewArray::new(
                    view.views().clone(),
                    Arc::clone(view.data_buffers()),
                    nulls,
                ))
            }
            DataType::BinaryView => {
                let view = array.as_binary_view();
                Arc::new(BinaryViewArray::new(
                    view.views().clone(),
                    Arc::clone(view.data_buffers()),
                    nulls,
                ))
            }
            _ => unreachable!("view type checked above"),
        })
    }
}

#[inline]
fn set_missing_bits(
    words: &mut [u64; MISSING_WORDS],
    mut offset: usize,
    mut count: usize,
) {
    while count != 0 {
        let word_idx = offset / (u64::BITS as usize);
        let bit_offset = offset % (u64::BITS as usize);
        let take = count.min(u64::BITS as usize - bit_offset);
        words[word_idx] |= (u64::MAX >> (u64::BITS as usize - take)) << bit_offset;
        offset += take;
        count -= take;
    }
}

/// Borrow a single shifted slice and mask targets that leave their SQL partition.
/// The caller reserves expression scratch and bounds each leaf to one work quantum.
/// A missing physical span or a default/encoding that needs materialization
/// delegates to the segmented history evaluator.
pub(super) fn try_shifted_input(
    neighbor: &Neighbor,
    input: NavigationInput<'_>,
    batch_start: usize,
    batch: &RecordBatch,
    start: usize,
    len: usize,
) -> Result<Option<ArrayRef>> {
    debug_assert!(len <= PACKED_CLASSIFY_CHUNK_ROWS);
    let column = batch.column(neighbor.column);
    if neighbor.shift == 0
        || (column.data_type() == &DataType::Null && neighbor.default.is_none())
    {
        return Ok(Some(column.slice(start, len)));
    }
    let distance = neighbor.shift.unsigned_abs() as usize;
    let previous = neighbor.shift < 0;
    let shifted = if previous {
        start.checked_sub(distance)
    } else {
        start.checked_add(distance)
    };
    let Some(shifted) = shifted.filter(|&row| row <= batch.num_rows() - len) else {
        return Ok(None);
    };

    let first_row = batch_start + start;
    let limit = first_row + len;
    let mut row = first_row;
    let mut index = input.ranges.partition_point(|p| p.end <= row);
    let mut missing = [0u64; MISSING_WORDS];
    let mut any_missing = false;
    while row < limit {
        let partition = &input.ranges[index];
        let stop = partition.end.min(limit);
        let absolute = input.origin + row;
        let count = stop - row;
        let (offset, n) = if previous {
            let lower = if index == 0 {
                input.first_start
            } else {
                input.origin + partition.start
            };
            let n = lower
                .saturating_add(distance)
                .saturating_sub(absolute)
                .min(count);
            (row - first_row, n)
        } else {
            let upper = if index + 1 == input.ranges.len() {
                input.last_end
            } else {
                input.origin + partition.end
            };
            let valid = upper
                .saturating_sub(distance)
                .saturating_sub(absolute)
                .min(count);
            (row - first_row + valid, count - valid)
        };
        if n != 0 {
            if neighbor.default.is_some()
                || matches!(
                    column.data_type(),
                    DataType::Union(..) | DataType::RunEndEncoded(..)
                )
            {
                return Ok(None);
            }
            set_missing_bits(&mut missing, offset, n);
            any_missing = true;
        }
        row = stop;
        index += 1;
    }
    let values = column.slice(shifted, len);
    if !any_missing {
        return Ok(Some(values));
    }
    let word_count = len.div_ceil(u64::BITS as usize);
    let mut bytes = [0u8; PACKED_CLASSIFY_CHUNK_ROWS / 8];
    for (i, &word) in missing[..word_count].iter().enumerate() {
        bytes[i * 8..(i + 1) * 8].copy_from_slice(&word.to_le_bytes());
    }
    let byte_len = len.div_ceil(8);
    let flags = BooleanArray::new(
        BooleanBuffer::new(Buffer::from_slice_ref(&bytes[..byte_len]), 0, len),
        None,
    );
    Ok(Some(Neighbor::mask_array_with_nulls(&values, &flags)?))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::execution::classification::navigation::{
        OffsetExpression, StaticNavigation, StaticRule,
    };
    use crate::execution::common::memory::new_unbounded_state_memory;
    use crate::execution::common::nulls::is_logically_null;
    use crate::execution::storage::history_buffer::SharedHistoryBuffer;
    use datafusion::arrow::array::{
        Decimal128Array, DictionaryArray, Int8Array, Int32Array, NullArray, RunArray,
        StringArray, UnionArray,
    };
    use datafusion::arrow::datatypes::{Field, Int8Type, Int32Type, Schema, UnionFields};
    use datafusion::arrow::util::display::array_value_to_string;
    use datafusion::common::ScalarValue;
    use datafusion::physical_expr::expressions::{Column, IsNotNullExpr, IsNullExpr};
    use datafusion::physical_plan::PhysicalExpr;

    #[test]
    fn shifted_view_mask_shares_buffers() -> Result<()> {
        let text = "an out-of-line string";
        let source = StringViewArray::from(vec![
            Some(text),
            Some(text),
            Some(text),
            None,
            Some(text),
            Some(text),
            Some(text),
            Some(text),
        ]);
        let source = source.slice(1, 6);
        let table = Arc::clone(source.data_buffers());
        let batch = RecordBatch::try_from_iter([("v", Arc::new(source) as ArrayRef)])?;
        let output = try_shifted_input(
            &Neighbor {
                column: 0,
                shift: 1,
                default: None,
            },
            NavigationInput {
                origin: 0,
                ranges: &[0..3, 3..6],
                first_start: 0,
                last_end: 6,
            },
            0,
            &batch,
            1,
            4,
        )?
        .unwrap();
        let view = output.as_string_view();
        assert!(Arc::ptr_eq(&table, view.data_buffers()));
        assert_eq!(
            view.views().as_ptr(),
            batch.column(0).as_string_view().views()[2..].as_ptr()
        );
        assert_eq!(
            view.iter().collect::<Vec<_>>(),
            [None, None, Some(text), Some(text)]
        );
        Ok(())
    }

    fn source() -> Result<RecordBatch> {
        let numbers: Vec<_> = (0..101).map(|i: i32| (i % 5 != 0).then_some(i)).collect();
        let strings: Vec<_> = numbers
            .iter()
            .map(|v| v.map(|n| format!("value-{n}")))
            .collect();
        let tags: Vec<_> = (0..101).map(|i| if i % 2 == 0 { 1i8 } else { 4 }).collect();
        let fields: UnionFields = [1, 4]
            .into_iter()
            .map(|tag| {
                (
                    tag,
                    Arc::new(Field::new(format!("v{tag}"), DataType::Int32, true)),
                )
            })
            .collect();
        let union = UnionArray::try_new(
            fields,
            tags.into(),
            None,
            vec![
                Arc::new(Int32Array::from(numbers.clone())),
                Arc::new(Int32Array::from_iter(numbers.iter().map(|n| n.map(|n| -n)))),
            ],
        )?;
        let dict = DictionaryArray::<Int8Type>::try_new(
            Int8Array::from_iter(numbers.iter().map(|n| n.map(|n| (n % 3) as i8))),
            Arc::new(StringArray::from(vec![Some("a"), None, Some("c")])),
        )?;
        let run = RunArray::<Int32Type>::try_new(
            &Int32Array::from(vec![7, 19, 48, 91, 101]),
            &StringArray::from(vec![None, Some("r1"), None, Some("r3"), None]),
        )?;
        let columns: Vec<ArrayRef> = vec![
            Arc::new(NullArray::new(101)),
            Arc::new(
                Decimal128Array::from_iter(numbers.iter().map(|n| n.map(i128::from)))
                    .with_precision_and_scale(18, 2)?,
            ),
            Arc::new(StringArray::from_iter(strings.iter().map(|s| s.as_deref()))),
            Arc::new(StringViewArray::from_iter(
                strings.iter().map(|s| s.as_deref()),
            )),
            Arc::new(dict),
            Arc::new(union),
            Arc::new(run),
        ];
        let schema = Schema::new(
            columns
                .iter()
                .enumerate()
                .map(|(i, a)| {
                    Field::new(format!("value_{i}"), a.data_type().clone(), true)
                })
                .collect::<Vec<_>>(),
        );
        Ok(RecordBatch::try_new(Arc::new(schema), columns)?)
    }

    #[test]
    fn shifted_nulls_and_values_respect_partition_and_batch_edges() -> Result<()> {
        let raw = source()?;
        let memory = new_unbounded_state_memory();
        let mut history = SharedHistoryBuffer::new(raw.schema(), memory.new_empty());
        for at in (0..raw.num_rows()).step_by(5) {
            history.append(raw.slice(at, (raw.num_rows() - at).min(5)))?;
        }
        // The head is the middle of retained history. The first and last
        // logical partitions continue outside it. Interior groups include
        // lengths one, two, three, and more than one work quantum.
        let head = 4..98;
        let partitions: [std::ops::Range<usize>; 7] =
            [0..7, 7..8, 8..10, 10..13, 13..82, 82..84, 84..101];
        let ranges: Vec<_> = partitions
            .iter()
            .map(|p| p.start.saturating_sub(head.start)..p.end.min(head.end) - head.start)
            .collect();
        let input = NavigationInput {
            ranges: &ranges,
            origin: head.start,
            first_start: 0,
            last_end: raw.num_rows(),
        };
        for (column, values) in raw.columns().iter().enumerate() {
            for shift in [-11, -3, -2, -1, 0, 1, 2, 3, 11] {
                let neighbor = Neighbor {
                    column,
                    shift,
                    default: None,
                };
                let mut nav = StaticNavigation::default();
                let schema = Arc::new(Schema::new(vec![Field::new(
                    "v",
                    values.data_type().clone(),
                    true,
                )]));
                let leaf = Arc::new(Column::new("v", 0));
                for (is_null, bit) in [(true, 1), (false, 2)] {
                    let predicate: Arc<dyn PhysicalExpr> = if is_null {
                        Arc::new(IsNullExpr::new(leaf.clone()))
                    } else {
                        Arc::new(IsNotNullExpr::new(leaf.clone()))
                    };
                    // Encoded inputs keep the existing native null-check route.
                    let expr = OffsetExpression::try_new(
                        predicate,
                        vec![neighbor.clone()],
                        schema.clone(),
                    );
                    let rule = expr.map_or_else(
                        || StaticRule::IsNull(neighbor.clone(), is_null),
                        StaticRule::Expr,
                    );
                    nav.add(rule, bit).unwrap();
                }
                for batch_size in [3, 7, 8192] {
                    for at in (0..head.len()).step_by(batch_size) {
                        let batch =
                            raw.slice(head.start + at, (head.len() - at).min(batch_size));
                        for start in (0..batch.num_rows()).step_by(16) {
                            let len = (batch.num_rows() - start).min(16);
                            let leaf = try_shifted_input(
                                &neighbor, input, at, &batch, start, len,
                            )?;
                            let mut masks = vec![0; len];
                            nav.classify(
                                &history,
                                input,
                                (at, &batch),
                                start,
                                &mut masks,
                                &memory,
                            )?;
                            for (i, mask) in masks.into_iter().enumerate() {
                                let row = head.start + at + start + i;
                                let partition = &partitions
                                    [partitions.partition_point(|p| p.end <= row)];
                                let target = row
                                    .checked_add_signed(shift as isize)
                                    .filter(|r| partition.contains(r));
                                let null = target.is_none_or(|j| {
                                    is_logically_null(values.as_ref(), j)
                                });
                                assert_eq!(
                                    mask,
                                    if null { 1 } else { 2 },
                                    "{:?} {row} {shift}",
                                    values.data_type()
                                );
                                if let Some(leaf) = &leaf {
                                    assert_eq!(is_logically_null(leaf.as_ref(), i), null);
                                    if !null {
                                        assert_eq!(
                                            array_value_to_string(leaf, i)?,
                                            array_value_to_string(
                                                values,
                                                target.unwrap()
                                            )?
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    #[test]
    fn try_shifted_input_masks_partition_edges_across_wide_chunks() -> Result<()> {
        let total = PACKED_CLASSIFY_CHUNK_ROWS + 80;
        let values: Vec<Option<i32>> = (0..total)
            .map(|i| (i % 7 != 0).then_some(i as i32))
            .collect();
        let array: ArrayRef = Arc::new(Int32Array::from(values.clone()));
        let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int32, true)]));
        let batch = RecordBatch::try_new(schema, vec![Arc::clone(&array)])?;
        // Mix tiny, 64-boundary, and wide partitions inside one 512-row chunk.
        let partitions: Vec<std::ops::Range<usize>> = vec![
            0..1,
            1..3,
            3..64,
            64..65,
            65..131,
            131..260,
            260..512,
            512..540,
            540..total,
        ];
        let input = NavigationInput {
            ranges: &partitions,
            origin: 0,
            first_start: 0,
            last_end: total,
        };
        for shift in [-3, -1, 1, 3] {
            let neighbor = Neighbor {
                column: 0,
                shift,
                default: None,
            };
            let start = if shift < 0 { 10 } else { 0 };
            for len in [200, PACKED_CLASSIFY_CHUNK_ROWS] {
                let leaf = try_shifted_input(&neighbor, input, 0, &batch, start, len)?
                    .expect("interior shifted slice stays on fast path");
                let out = leaf.as_any().downcast_ref::<Int32Array>().unwrap();
                assert_eq!(out.len(), len);
                for i in 0..len {
                    let row = start + i;
                    let partition =
                        &partitions[partitions.partition_point(|p| p.end <= row)];
                    let expected = row
                        .checked_add_signed(shift as isize)
                        .filter(|r| partition.contains(r))
                        .and_then(|j| values[j]);
                    if let Some(v) = expected {
                        assert!(out.is_valid(i), "shift={shift} len={len} row={row}");
                        assert_eq!(out.value(i), v);
                    } else {
                        assert!(out.is_null(i), "shift={shift} len={len} row={row}");
                    }
                }
            }
        }
        Ok(())
    }

    #[test]
    fn explicit_defaults_only_require_filling_when_the_shift_leaves_its_partition()
    -> Result<()> {
        let values: ArrayRef = Arc::new(Int32Array::from(vec![
            Some(11),
            None,
            Some(13),
            None,
            Some(15),
            Some(16),
        ]));
        let batch = RecordBatch::try_from_iter([("v", Arc::clone(&values))])?;
        let neighbor = Neighbor {
            column: 0,
            shift: 1,
            default: Some(Arc::new(ScalarValue::Int32(Some(99)))),
        };
        let input = NavigationInput {
            ranges: &[0..3, 3..6],
            origin: 0,
            first_start: 0,
            last_end: 6,
        };
        let valid = try_shifted_input(&neighbor, input, 0, &batch, 0, 2)?.unwrap();
        assert!(valid.is_null(0));
        assert_eq!(array_value_to_string(&valid, 1)?, "13");
        assert!(try_shifted_input(&neighbor, input, 0, &batch, 0, 4)?.is_none());
        Ok(())
    }
}