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

//! Shared helper utilities for navigation window UDF evaluators.
//!
//! These routines validate classifier-mask inputs and perform array extraction
//! used by PREV/NEXT/FIRST/LAST evaluators.

use datafusion::arrow::array::{Array, ArrayRef, BooleanArray, UInt64Array, make_array};
use datafusion::common::{
    Result, ScalarValue, arrow_datafusion_err, exec_datafusion_err,
};
use datafusion_hash_grouped_order::gather::interleave_compact;

use crate::execution::storage::{
    canonical_interleave_type, contains_run_end_encoded, retype_gather_data,
};

use crate::functions::navigation_common::nullable_navigation_data_type;
pub(super) use datafusion_hash_grouped_order::gather::contains_dictionary;
use datafusion_hash_grouped_order::gather::take_compat;

/// Materialize the declared navigation type regardless of this partition's NULLs.
pub(super) fn nullable_navigation_array(array: &ArrayRef) -> Result<ArrayRef> {
    if !contains_run_end_encoded(array.data_type()) {
        return Ok(std::sync::Arc::clone(array));
    }
    Ok(make_array(retype_gather_data(
        array.to_data(),
        &nullable_navigation_data_type(array.data_type()),
        false,
    )?))
}

pub(super) fn get_classifier_mask(values: &[ArrayRef]) -> Result<&BooleanArray> {
    // The classifier mask is the last argument when present.
    // The caller ensures it is only invoked when the mask exists.
    values
        .last()
        .and_then(|a| a.as_any().downcast_ref::<BooleanArray>())
        .ok_or_else(|| {
            exec_datafusion_err!("classifier mask column must be a BooleanArray")
        })
}

fn align_default_run_end_type(
    array: ArrayRef,
    target_type: &datafusion::arrow::datatypes::DataType,
) -> Result<ArrayRef> {
    if contains_run_end_encoded(target_type)
        && array.data_type() != target_type
        && canonical_interleave_type(array.data_type())?
            == canonical_interleave_type(target_type)?
    {
        return Ok(make_array(retype_gather_data(
            array.to_data(),
            target_type,
            false,
        )?));
    }
    Ok(array)
}

pub(super) fn gather_array_by_indices(
    data_arr: &ArrayRef,
    indices: Vec<Option<usize>>,
) -> Result<ArrayRef> {
    let idx_array = UInt64Array::from_iter(
        indices
            .into_iter()
            .map(|index| index.map(|value| value as u64)),
    );
    let data_arr = nullable_navigation_array(data_arr)?;
    take_compat(data_arr.as_ref(), &idx_array).map_err(|e| arrow_datafusion_err!(e))
}

pub(super) fn gather_with_default(
    data_arr: &ArrayRef,
    indices: Vec<Option<usize>>,
    default_value: &ScalarValue,
) -> Result<ArrayRef> {
    // Handle an empty source and all-missing targets before invoking take.
    if indices.iter().all(Option::is_none) {
        let target_type = nullable_navigation_data_type(data_arr.data_type());
        let result =
            nullable_navigation_array(&default_value.to_array_of_size(indices.len())?)?;
        return align_default_run_end_type(result, &target_type);
    }
    if default_value.is_null() || indices.iter().all(Option::is_some) {
        return gather_array_by_indices(data_arr, indices);
    }
    let data_arr = nullable_navigation_array(data_arr)?;
    let default_one = align_default_run_end_type(
        nullable_navigation_array(&default_value.to_array_of_size(1)?)?,
        data_arr.data_type(),
    )?;
    let pairs: Vec<(usize, usize)> = indices
        .into_iter()
        .map(|idx| match idx {
            Some(row) => (0, row),
            None => (1, 0),
        })
        .collect();
    interleave_compact(&[data_arr.as_ref(), default_one.as_ref()], &pairs)
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use datafusion::arrow::array::{Array, ArrayRef, StructArray};
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion::arrow::record_batch::RecordBatch;
    use datafusion::common::ScalarValue;

    use super::{contains_dictionary, gather_array_by_indices, gather_with_default};
    use crate::functions::navigation_common::{
        NavigationKind, navigation_return_field, resolve_navigation_default,
        test_support::{assert_run_values, custom_run_array},
    };

    #[test]
    fn navigation_results_match_declared_run_field() -> datafusion::common::Result<()> {
        let data = custom_run_array(false);
        let input = Arc::new(Field::new("input", data.data_type().clone(), false));
        let field = navigation_return_field(NavigationKind::First, &[input], "result");
        let schema = Arc::new(Schema::new(vec![field]));
        let default =
            resolve_navigation_default(&ScalarValue::Null, schema.field(0).data_type())?;
        let mut partitions = Vec::new();
        for indices in [vec![None, Some(0)], vec![Some(1), Some(0)]] {
            for result in [
                gather_array_by_indices(&data, indices.clone())?,
                gather_with_default(&data, indices, &default)?,
            ] {
                assert_eq!(result.data_type(), custom_run_array(true).data_type());
                RecordBatch::try_new(Arc::clone(&schema), vec![Arc::clone(&result)])?;
                partitions.push(result);
            }
        }
        let arrays: Vec<_> = partitions.iter().map(|array| array.as_ref()).collect();
        let combined = datafusion::arrow::compute::concat(&arrays)?;
        RecordBatch::try_new(schema, vec![combined])?;
        Ok(())
    }

    #[test]
    fn required_run_values_allow_missing_targets_and_defaults() {
        let data = custom_run_array(false);
        for indices in [vec![None, Some(0)], vec![None, None]] {
            let result = gather_array_by_indices(&data, indices.clone()).unwrap();
            assert_eq!(result.data_type(), custom_run_array(true).data_type());
            let expected: Vec<_> =
                indices.iter().map(|index| index.map(|_| 10)).collect();
            assert_run_values(&result, &expected);

            for default in [Some(7), None] {
                let scalar = resolve_navigation_default(
                    &ScalarValue::Int32(default),
                    data.data_type(),
                )
                .unwrap();
                let result =
                    gather_with_default(&data, indices.clone(), &scalar).unwrap();
                let expected: Vec<_> = indices
                    .iter()
                    .map(|index| index.map_or(default, |_| Some(10)))
                    .collect();
                assert_run_values(&result, &expected);
                assert_eq!(result.data_type(), custom_run_array(true).data_type());
            }
        }
        // An all-default result must not attempt to read dummy index zero.
        for default in [Some(7), None] {
            let scalar = resolve_navigation_default(
                &ScalarValue::Int32(default),
                data.data_type(),
            )
            .unwrap();
            let result =
                gather_with_default(&data.slice(0, 0), vec![None; 2], &scalar).unwrap();
            assert_run_values(&result, &[default; 2]);
        }
    }

    #[test]
    fn nested_required_run_values_allow_missing_targets() {
        let encoded = custom_run_array(false);
        let data: ArrayRef = Arc::new(StructArray::new(
            vec![Arc::new(Field::new(
                "nested",
                encoded.data_type().clone(),
                true,
            ))]
            .into(),
            vec![encoded],
            None,
        ));
        let result = gather_array_by_indices(&data, vec![None, Some(0)]).unwrap();
        let result = result.as_any().downcast_ref::<StructArray>().unwrap();
        assert!(result.is_null(0));
        assert_run_values(result.column(0), &[None, Some(10)]);
        assert_eq!(
            result.column(0).data_type(),
            custom_run_array(true).data_type()
        );
    }

    #[test]
    fn non_null_container_default_can_have_a_null_run_child() {
        let encoded = custom_run_array(false);
        let data: ArrayRef = Arc::new(StructArray::new(
            vec![Arc::new(Field::new(
                "nested",
                encoded.data_type().clone(),
                true,
            ))]
            .into(),
            vec![encoded],
            None,
        ));
        let null_child = resolve_navigation_default(
            &ScalarValue::Null,
            custom_run_array(true).data_type(),
        )
        .unwrap()
        .to_array()
        .unwrap();
        let default = StructArray::new(
            vec![Arc::new(Field::new(
                "nested",
                null_child.data_type().clone(),
                true,
            ))]
            .into(),
            vec![null_child],
            None,
        );
        let default = resolve_navigation_default(
            &ScalarValue::try_from_array(&default, 0).unwrap(),
            data.data_type(),
        )
        .unwrap();
        assert!(!default.is_null());
        let result = gather_with_default(&data, vec![None, Some(0)], &default).unwrap();
        let result = result.as_any().downcast_ref::<StructArray>().unwrap();
        assert!(result.is_valid(0));
        assert_run_values(result.column(0), &[None, Some(10)]);
        assert_eq!(
            result.column(0).data_type(),
            custom_run_array(true).data_type()
        );
    }

    #[test]
    fn dictionary_detection_includes_nested_types() {
        let dictionary =
            DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8));
        let field = Arc::new(Field::new("nested", dictionary.clone(), true));
        for data_type in [
            dictionary,
            DataType::List(Arc::clone(&field)),
            DataType::Struct(vec![Arc::clone(&field)].into()),
            DataType::RunEndEncoded(
                Arc::new(Field::new("ends", DataType::Int32, false)),
                field,
            ),
        ] {
            assert!(contains_dictionary(&data_type));
        }
        assert!(!contains_dictionary(custom_run_array(false).data_type()));
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn gather_keeps_indices_above_u32_max() {
        use datafusion::arrow::array::{Int32Array, Int64Array, RunArray};
        use datafusion::arrow::datatypes::Int64Type;

        // Run-end encoding gives a wide logical index with two physical values.
        let first_run_end = i64::from(u32::MAX) + 1;
        let run_ends = Int64Array::from(vec![first_run_end, first_run_end + 1]);
        let values = Int32Array::from(vec![10, 20]);
        let encoded = RunArray::<Int64Type>::try_new(&run_ends, &values).unwrap();
        let data: ArrayRef = Arc::new(encoded);
        let index = u32::MAX as usize + 1;
        assert!(index < data.len());

        let gathered = gather_array_by_indices(&data, vec![Some(index)]).unwrap();
        let gathered = gathered
            .as_any()
            .downcast_ref::<RunArray<Int64Type>>()
            .unwrap();
        assert_eq!(gathered.len(), 1);
        let values = gathered
            .values()
            .as_any()
            .downcast_ref::<Int32Array>()
            .unwrap();
        assert_eq!(values.value(0), 20);
    }

    #[test]
    fn gather_with_default_preserves_custom_nested_ree_across_interleave_and_dict_overflow()
    -> datafusion::common::Result<()> {
        use datafusion::arrow::array::{
            DictionaryArray, Int8Array, Int32Array, ListArray, RunArray, StringArray,
        };
        use datafusion::arrow::buffer::OffsetBuffer;
        use datafusion::arrow::datatypes::{Int8Type, Int32Type};

        // 1. Struct<d: Dictionary<Int8, Utf8> (128 values), r: custom REE> with non-null
        // default that adds a 129th dictionary entry (previously triggered Arrow zip's
        // dictionary-overflow fallback to interleave and failed on custom REE field names).
        let dict_values = Arc::new(StringArray::from_iter_values(
            (0..128).map(|i| format!("v{i}")),
        ));
        let dict_keys = Int8Array::from(vec![0_i8, 1_i8]);
        let dict_arr: ArrayRef = Arc::new(DictionaryArray::<Int8Type>::try_new(
            dict_keys,
            dict_values,
        )?);
        let ree_arr = custom_run_array(false);
        let struct_fields: datafusion::arrow::datatypes::Fields = vec![
            Arc::new(Field::new("d", dict_arr.data_type().clone(), true)),
            Arc::new(Field::new("r", ree_arr.data_type().clone(), true)),
        ]
        .into();
        let data: ArrayRef = Arc::new(StructArray::try_new(
            struct_fields.clone(),
            vec![Arc::clone(&dict_arr), Arc::clone(&ree_arr)],
            None,
        )?);
        let default_dict: ArrayRef = Arc::new(DictionaryArray::<Int8Type>::try_new(
            Int8Array::from(vec![0_i8]),
            Arc::new(StringArray::from(vec!["fallback"])),
        )?);
        let default_ree = custom_run_array(true).slice(0, 1);
        let default_struct = StructArray::try_new(
            vec![
                Arc::new(Field::new("d", default_dict.data_type().clone(), true)),
                Arc::new(Field::new("r", default_ree.data_type().clone(), true)),
            ]
            .into(),
            vec![default_dict, default_ree],
            None,
        )?;
        let default_scalar = ScalarValue::Struct(Arc::new(default_struct));
        let gathered = gather_with_default(&data, vec![None, Some(1)], &default_scalar)?;
        let expected_type =
            crate::functions::navigation_common::nullable_navigation_data_type(
                data.data_type(),
            );
        assert_eq!(gathered.data_type(), &expected_type);
        assert_eq!(gathered.len(), 2);

        // 2. List<custom REE> over 1024 alternating rows (previously triggered Arrow zip's
        // `should_use_interleave` path and panicked inside GenericListArray::new).
        let list_item = Arc::new(Field::new("item", ree_arr.data_type().clone(), true));
        let list_data: ArrayRef = Arc::new(ListArray::try_new(
            Arc::clone(&list_item),
            OffsetBuffer::new(vec![0_i32, 1, 2].into()),
            Arc::clone(&ree_arr),
            None,
        )?);
        let default_run: ArrayRef = Arc::new(RunArray::<Int32Type>::try_new(
            &Int32Array::from(vec![1]),
            &Int32Array::from(vec![Some(99)]),
        )?);
        let default_list = ListArray::try_new(
            Arc::new(Field::new("item", default_run.data_type().clone(), true)),
            OffsetBuffer::new(vec![0_i32, 1].into()),
            default_run,
            None,
        )?;
        let default_list_scalar = ScalarValue::List(Arc::new(default_list));
        let alternating: Vec<Option<usize>> = (0..1024)
            .map(|i| if i % 2 == 0 { Some(i % 2) } else { None })
            .collect();
        let gathered_list =
            gather_with_default(&list_data, alternating, &default_list_scalar)?;
        assert_eq!(
            gathered_list.data_type(),
            &crate::functions::navigation_common::nullable_navigation_data_type(
                list_data.data_type()
            )
        );
        assert_eq!(gathered_list.len(), 1024);
        Ok(())
    }
}