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
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
// 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 std::ops::Range;
use std::sync::Arc;

use datafusion::arrow::array::{Array, ArrayRef, new_null_array};
use datafusion::arrow::compute::concat;
use datafusion::arrow::datatypes::DataType;
use datafusion::common::{Result, ScalarValue, arrow_datafusion_err};
use datafusion::logical_expr::PartitionEvaluator;

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

use super::helpers::{
    contains_dictionary, gather_with_default, get_classifier_mask,
    nullable_navigation_array,
};
use super::mask_cache::{map_nth_last_matches, nth_first_match_index};

/// Shift values right for `PREV` or left for `NEXT` by `offset` rows, filling
/// vacated positions with `default_value`. An offset at or beyond `array.len()`
/// produces defaults throughout.
fn shift_with_default_value(
    array: &ArrayRef,
    kind: NavigationKind,
    offset: usize,
    default_value: &ScalarValue,
) -> Result<ArrayRef> {
    let len = array.len();
    if offset == 0 {
        return Ok(Arc::clone(array));
    }
    if offset >= len {
        return default_value.to_array_of_size(len);
    }

    let kept_len = len - offset;
    let default_values = default_value.to_array_of_size(offset)?;
    match kind {
        NavigationKind::Prev => {
            let slice = array.slice(0, kept_len);
            concat(&[default_values.as_ref(), slice.as_ref()])
                .map_err(|e| arrow_datafusion_err!(e))
        }
        NavigationKind::Next => {
            let slice = array.slice(offset, kept_len);
            concat(&[slice.as_ref(), default_values.as_ref()])
                .map_err(|e| arrow_datafusion_err!(e))
        }
        NavigationKind::First | NavigationKind::Last => unreachable!(),
    }
}

#[derive(Debug)]
pub(crate) struct MatchRecognizeShiftEvaluator {
    pub(super) mask_provided: bool,
    pub(super) anchor: LogicalAnchor,
    pub(super) offset: usize,
    pub(super) default_value: ScalarValue,
    pub(super) kind: NavigationKind,
    bounded_execution: bool,
    resolved_default: Option<(DataType, ScalarValue)>,
}

impl MatchRecognizeShiftEvaluator {
    pub(crate) fn new(
        mask_provided: bool,
        anchor: LogicalAnchor,
        offset: usize,
        default_value: ScalarValue,
        kind: NavigationKind,
        value_type: &DataType,
    ) -> Self {
        debug_assert!(kind.is_shift());
        let bounded_execution = if value_type.is_null() {
            !contains_dictionary(&default_value.data_type())
        } else {
            !contains_dictionary(value_type)
        };
        Self {
            mask_provided,
            anchor,
            offset,
            kind,
            bounded_execution,
            default_value,
            resolved_default: None,
        }
    }

    fn resolve_cached_default(&mut self, target_type: &DataType) -> Result<&ScalarValue> {
        let cache_hit = matches!(
            &self.resolved_default,
            Some((cached_type, _)) if cached_type == target_type
        );
        if !cache_hit {
            let resolved = resolve_navigation_default(&self.default_value, target_type)?;
            return Ok(&self
                .resolved_default
                .insert((target_type.clone(), resolved))
                .1);
        }
        match self.resolved_default.as_ref() {
            Some((_, resolved)) => Ok(resolved),
            None => unreachable!(),
        }
    }
}

impl PartitionEvaluator for MatchRecognizeShiftEvaluator {
    fn get_range(&self, idx: usize, num_rows: usize) -> Result<Range<usize>> {
        // DataFusion uses this range both to retain required history and to
        // decide when a noncausal result must wait for more input.
        Ok(match self.kind {
            NavigationKind::Prev => {
                idx.saturating_sub(self.offset)..idx.saturating_add(1)
            }
            // The native LEAD convention uses the target index as the end:
            // end == num_rows means the target has not arrived yet. Offset zero
            // may therefore return idx..idx, while the current row is present.
            NavigationKind::Next => idx..idx.saturating_add(self.offset).min(num_rows),
            NavigationKind::First | NavigationKind::Last => unreachable!(),
        })
    }

    fn evaluate_all(&mut self, values: &[ArrayRef], num_rows: usize) -> Result<ArrayRef> {
        let owned_nulls;
        let data_arr = if values[0].data_type().is_null() {
            let default_type =
                nullable_navigation_data_type(&self.default_value.data_type());
            if !default_type.is_null() {
                owned_nulls = new_null_array(&default_type, values[0].len());
                &owned_nulls
            } else {
                &values[0]
            }
        } else {
            &values[0]
        };
        let data_arr = &nullable_navigation_array(data_arr)?;

        if !self.mask_provided {
            let (kind, offset) = (self.kind, self.offset);
            let default_val = self.resolve_cached_default(data_arr.data_type())?;
            return shift_with_default_value(data_arr, kind, offset, default_val);
        }

        // Validate and cache the default before mask checks to keep error
        // timing consistent with unmasked evaluation.
        self.resolve_cached_default(data_arr.data_type())?;

        let mask_arr = get_classifier_mask(values)?;

        // With bounded execution disabled for masked NEXT/PREV, the mask should always
        // cover all rows being evaluated. If not, there's a bug in partition construction.
        if mask_arr.len() != data_arr.len() {
            return Err(datafusion::common::DataFusionError::Internal(format!(
                "Mask length {} does not match data length {} in MATCH_RECOGNIZE window function",
                mask_arr.len(),
                data_arr.len()
            )));
        }

        let gather_indices = match self.anchor {
            LogicalAnchor::First(lo) => {
                let nth_idx = nth_first_match_index(mask_arr, lo);
                (0..num_rows)
                    .map(|idx| {
                        nth_idx.filter(|&anchor| idx >= anchor).and_then(|anchor| {
                            self.kind.checked_target(anchor, self.offset, num_rows)
                        })
                    })
                    .collect()
            }
            LogicalAnchor::Last(lo) => {
                map_nth_last_matches(mask_arr, num_rows, lo, |anchor| {
                    anchor.and_then(|anchor| {
                        self.kind.checked_target(anchor, self.offset, num_rows)
                    })
                })?
            }
        };

        let default_val = self.resolve_cached_default(data_arr.data_type())?;
        gather_with_default(data_arr, gather_indices, default_val)
    }

    fn evaluate(
        &mut self,
        values: &[ArrayRef],
        range: &Range<usize>,
    ) -> Result<ScalarValue> {
        if self.mask_provided {
            return datafusion::common::internal_err!(
                "masked navigation requires whole-partition evaluate_all"
            );
        }
        let data_arr = &nullable_navigation_array(&values[0])?;
        let owned_default_type;
        let (normalize_null, target_type) = if data_arr.data_type().is_null() {
            owned_default_type =
                nullable_navigation_data_type(&self.default_value.data_type());
            if !owned_default_type.is_null() {
                (true, &owned_default_type)
            } else {
                (false, data_arr.data_type())
            }
        } else {
            (false, data_arr.data_type())
        };

        // Resolve and cache once per target type so invalid default casts still
        // fail on the first row while avoiding per-row ScalarValue::cast_to.
        self.resolve_cached_default(target_type)?;

        // Ranges and value arrays share DataFusion's current buffer coordinates,
        // including after pruning. PREV retains history before the current row;
        // NEXT starts at the current row and extends towards its target.
        let row_index = match self.kind {
            NavigationKind::Prev => range.end.checked_sub(1),
            NavigationKind::Next => Some(range.start),
            NavigationKind::First | NavigationKind::Last => unreachable!(),
        }
        .filter(|&idx| idx < data_arr.len());

        let target = row_index.and_then(|row_index| {
            self.kind
                .checked_target(row_index, self.offset, data_arr.len())
        });

        match target {
            Some(target_index) => {
                if normalize_null {
                    ScalarValue::try_from(target_type)
                } else {
                    ScalarValue::try_from_array(data_arr.as_ref(), target_index)
                }
            }
            None => Ok(self.resolve_cached_default(target_type)?.clone()),
        }
    }

    fn supports_bounded_execution(&self) -> bool {
        // When a classifier mask is present (symbol-qualified NEXT/PREV), we need
        // the entire partition to identify the last row matched to symbol X.
        // Batched execution would lose matched positions across batches.
        // Dictionary scalars must use array evaluation to avoid key overflow.
        !self.mask_provided && self.bounded_execution
    }

    fn is_causal(&self) -> bool {
        self.kind.is_causal()
    }
}

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

    use datafusion::arrow::array::{ArrayRef, BooleanArray, Int32Array, StringViewArray};

    use super::*;

    #[test]
    fn shifts_preserve_custom_run_fields_and_missing_defaults() -> Result<()> {
        use crate::functions::navigation_common::test_support::{
            assert_run_values, custom_run_array,
        };

        for nullable in [false, true] {
            for masked in [false, true] {
                for kind in [NavigationKind::Prev, NavigationKind::Next] {
                    for offset in [0, 1, 2] {
                        for default in [Some(7), None] {
                            let mut values = vec![custom_run_array(nullable)];
                            if masked {
                                values.push(Arc::new(BooleanArray::from(vec![
                                    false, true,
                                ])));
                            }
                            let mut evaluator = MatchRecognizeShiftEvaluator::new(
                                masked,
                                LogicalAnchor::Last(0),
                                offset,
                                ScalarValue::Int32(default),
                                kind,
                                values[0].data_type(),
                            );
                            let result = evaluator.evaluate_all(&values, 2)?;
                            let expected = if offset == 0 {
                                vec![if masked { default } else { Some(10) }, Some(20)]
                            } else if offset == 2 {
                                vec![default; 2]
                            } else if kind == NavigationKind::Prev {
                                vec![default, Some(10)]
                            } else if masked {
                                vec![default; 2]
                            } else {
                                vec![Some(20), default]
                            };
                            assert_run_values(&result, &expected);
                            assert_eq!(
                                result.data_type(),
                                custom_run_array(true).data_type()
                            );
                            if masked {
                                assert!(evaluator.evaluate(&values, &(0..1)).is_err());
                            } else {
                                // Bounded scalar collection also needs identical custom fields.
                                let scalars = (0..2)
                                    .map(|row| {
                                        let range = evaluator.get_range(row, 2)?;
                                        evaluator.evaluate(&values, &range)
                                    })
                                    .collect::<Result<Vec<_>>>()?;
                                let bounded = ScalarValue::iter_to_array(scalars)?;
                                assert_eq!(bounded.data_type(), result.data_type());
                                assert_run_values(&bounded, &expected);
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    #[test]
    fn dictionary_shifts_use_whole_partition_evaluation() -> Result<()> {
        use datafusion::arrow::array::{DictionaryArray, Int8Array, StringArray};
        use datafusion::arrow::datatypes::Int8Type;

        let data: ArrayRef = Arc::new(DictionaryArray::<Int8Type>::try_new(
            Int8Array::from(vec![0; 129]),
            Arc::new(StringArray::from(vec!["same"])),
        )?);
        for kind in [NavigationKind::Prev, NavigationKind::Next] {
            let mut evaluator = MatchRecognizeShiftEvaluator::new(
                false,
                LogicalAnchor::Last(0),
                1,
                ScalarValue::Utf8(Some("default".to_string())),
                kind,
                data.data_type(),
            );
            assert!(!evaluator.supports_bounded_execution());
            let result = evaluator.evaluate_all(&[Arc::clone(&data)], 129)?;
            assert_eq!(result.data_type(), data.data_type());
            assert_eq!(result.len(), 129);
            for row in 0..129 {
                let missing = (kind == NavigationKind::Prev && row == 0)
                    || (kind == NavigationKind::Next && row == 128);
                let expected = ScalarValue::Dictionary(
                    Box::new(DataType::Int8),
                    Box::new(ScalarValue::Utf8(Some(
                        if missing { "default" } else { "same" }.to_string(),
                    ))),
                );
                assert_eq!(ScalarValue::try_from_array(&result, row)?, expected);
            }
        }
        Ok(())
    }

    #[test]
    fn qualified_shift_uses_default_before_first_symbol_anchor() {
        let values: Vec<ArrayRef> = vec![
            Arc::new(Int32Array::from(vec![10, 20])),
            Arc::new(BooleanArray::from(vec![false, false])),
        ];

        for default in [Some(99), None] {
            for kind in [NavigationKind::Prev, NavigationKind::Next] {
                let mut evaluator = MatchRecognizeShiftEvaluator::new(
                    true,
                    LogicalAnchor::Last(0),
                    1,
                    ScalarValue::Int32(default),
                    kind,
                    &DataType::Int32,
                );

                let result = evaluator.evaluate_all(&values, values[0].len()).unwrap();
                let result = result.as_any().downcast_ref::<Int32Array>().unwrap();
                assert_eq!(result, &Int32Array::from(vec![default; 2]), "{kind:?}");
            }
        }
    }

    #[test]
    fn qualified_shift_materializes_long_string_defaults_without_an_anchor() {
        const DEFAULT: &str = "missing long default payload";
        let values: Vec<ArrayRef> = vec![
            Arc::new(StringViewArray::from(vec![Some("input"), None])),
            Arc::new(BooleanArray::from(vec![false, false])),
        ];
        for kind in [NavigationKind::Prev, NavigationKind::Next] {
            let mut evaluator = MatchRecognizeShiftEvaluator::new(
                true,
                LogicalAnchor::Last(0),
                1,
                ScalarValue::Utf8View(Some(DEFAULT.to_string())),
                kind,
                &DataType::Utf8View,
            );
            let result = evaluator.evaluate_all(&values, values[0].len()).unwrap();
            let result = result.as_any().downcast_ref::<StringViewArray>().unwrap();
            assert_eq!(
                result,
                &StringViewArray::from(vec![DEFAULT, DEFAULT]),
                "{kind:?}"
            );
        }
    }

    #[test]
    fn qualified_shift_preserves_sql_null_targets_alongside_non_null_defaults() {
        let values: Vec<ArrayRef> = vec![
            Arc::new(Int32Array::from(vec![None, Some(20), Some(30)])),
            Arc::new(BooleanArray::from(vec![false, true, true])),
        ];
        let mut evaluator = MatchRecognizeShiftEvaluator::new(
            true,
            LogicalAnchor::Last(0),
            1,
            ScalarValue::Int32(Some(99)),
            NavigationKind::Prev,
            &DataType::Int32,
        );
        let result = evaluator.evaluate_all(&values, values[0].len()).unwrap();
        let result = result.as_any().downcast_ref::<Int32Array>().unwrap();
        // Row 0 has no anchor (default 99), row 1 points to row 0 (SQL NULL),
        // row 2 points to row 1 (20).
        assert_eq!(result, &Int32Array::from(vec![Some(99), None, Some(20)]));
    }

    #[test]
    fn compound_shift_applies_physical_offset_from_logical_anchor() {
        // Row 0: halo (5), row 1: A (10), row 2: B (20), row 3: A (30), row 4: halo (40)
        let values: Vec<ArrayRef> = vec![
            Arc::new(Int32Array::from(vec![5, 10, 20, 30, 40])),
            Arc::new(BooleanArray::from(vec![false, true, false, true, false])),
        ];

        // PREV(FIRST(A.x, 0), 1, -1): first A is row 1 -> row 0 (5) once row 1 is reached
        let mut prev_first = MatchRecognizeShiftEvaluator::new(
            true,
            LogicalAnchor::First(0),
            1,
            ScalarValue::Int32(Some(-1)),
            NavigationKind::Prev,
            &DataType::Int32,
        );
        let out = prev_first.evaluate_all(&values, 5).unwrap();
        assert_eq!(
            out.as_any().downcast_ref::<Int32Array>().unwrap(),
            &Int32Array::from(vec![-1, 5, 5, 5, 5])
        );

        // NEXT(FIRST(A.x, 1), 1, -1): second A is row 3 -> row 4 (40) once row 3 is reached
        let mut next_first_1 = MatchRecognizeShiftEvaluator::new(
            true,
            LogicalAnchor::First(1),
            1,
            ScalarValue::Int32(Some(-1)),
            NavigationKind::Next,
            &DataType::Int32,
        );
        let out = next_first_1.evaluate_all(&values, 5).unwrap();
        assert_eq!(
            out.as_any().downcast_ref::<Int32Array>().unwrap(),
            &Int32Array::from(vec![-1, -1, -1, 40, 40])
        );

        // PREV(LAST(A.x, 1), 1, -1): at row 3, 1-before-last A is row 1 -> row 0 (5)
        let mut prev_last_1 = MatchRecognizeShiftEvaluator::new(
            true,
            LogicalAnchor::Last(1),
            1,
            ScalarValue::Int32(Some(-1)),
            NavigationKind::Prev,
            &DataType::Int32,
        );
        let out = prev_last_1.evaluate_all(&values, 5).unwrap();
        assert_eq!(
            out.as_any().downcast_ref::<Int32Array>().unwrap(),
            &Int32Array::from(vec![-1, -1, -1, 5, 5])
        );
    }

    #[test]
    fn shift_evaluator_normalizes_uncoerced_null_array_to_default_type() {
        use datafusion::arrow::array::{Int64Array, NullArray};

        // 1. Unmasked PREV/NEXT with uncoerced NullArray and concrete Int64 default (42).
        let unmasked_values: Vec<ArrayRef> = vec![Arc::new(NullArray::new(2))];
        let mut prev_unmasked = MatchRecognizeShiftEvaluator::new(
            false,
            LogicalAnchor::Last(0),
            1,
            ScalarValue::Int64(Some(42)),
            NavigationKind::Prev,
            &DataType::Null,
        );
        let prev_out = prev_unmasked.evaluate_all(&unmasked_values, 2).unwrap();
        assert_eq!(
            prev_out.as_any().downcast_ref::<Int64Array>().unwrap(),
            &Int64Array::from(vec![Some(42), None])
        );
        assert_eq!(
            prev_unmasked.evaluate(&unmasked_values, &(0..1)).unwrap(),
            ScalarValue::Int64(Some(42))
        );
        assert_eq!(
            prev_unmasked.evaluate(&unmasked_values, &(0..2)).unwrap(),
            ScalarValue::Int64(None)
        );

        let mut next_unmasked = MatchRecognizeShiftEvaluator::new(
            false,
            LogicalAnchor::Last(0),
            1,
            ScalarValue::Int64(Some(42)),
            NavigationKind::Next,
            &DataType::Null,
        );
        let next_out = next_unmasked.evaluate_all(&unmasked_values, 2).unwrap();
        assert_eq!(
            next_out.as_any().downcast_ref::<Int64Array>().unwrap(),
            &Int64Array::from(vec![None, Some(42)])
        );
        assert_eq!(
            next_unmasked.evaluate(&unmasked_values, &(0..2)).unwrap(),
            ScalarValue::Int64(None)
        );
        assert_eq!(
            next_unmasked.evaluate(&unmasked_values, &(1..2)).unwrap(),
            ScalarValue::Int64(Some(42))
        );

        // 2. Masked PREV/NEXT with uncoerced NullArray and concrete Int64 default (42).
        let masked_values: Vec<ArrayRef> = vec![
            Arc::new(NullArray::new(3)),
            Arc::new(BooleanArray::from(vec![false, true, true])),
        ];
        let mut prev_masked = MatchRecognizeShiftEvaluator::new(
            true,
            LogicalAnchor::Last(0),
            1,
            ScalarValue::Int64(Some(42)),
            NavigationKind::Prev,
            &DataType::Null,
        );
        let prev_masked_out = prev_masked.evaluate_all(&masked_values, 3).unwrap();
        assert_eq!(
            prev_masked_out
                .as_any()
                .downcast_ref::<Int64Array>()
                .unwrap(),
            &Int64Array::from(vec![Some(42), None, None])
        );

        let mut next_masked = MatchRecognizeShiftEvaluator::new(
            true,
            LogicalAnchor::Last(0),
            1,
            ScalarValue::Int64(Some(42)),
            NavigationKind::Next,
            &DataType::Null,
        );
        let next_masked_out = next_masked.evaluate_all(&masked_values, 3).unwrap();
        assert_eq!(
            next_masked_out
                .as_any()
                .downcast_ref::<Int64Array>()
                .unwrap(),
            &Int64Array::from(vec![Some(42), None, Some(42)])
        );

        // 3. Typed null default (Int64(None)) normalizes NullArray to Int64 nulls.
        let mut typed_null_default = MatchRecognizeShiftEvaluator::new(
            false,
            LogicalAnchor::Last(0),
            1,
            ScalarValue::Int64(None),
            NavigationKind::Prev,
            &DataType::Null,
        );
        let typed_null_out = typed_null_default
            .evaluate_all(&unmasked_values, 2)
            .unwrap();
        assert_eq!(
            typed_null_out
                .as_any()
                .downcast_ref::<Int64Array>()
                .unwrap(),
            &Int64Array::from(vec![None, None])
        );
        assert_eq!(
            typed_null_default
                .evaluate(&unmasked_values, &(0..2))
                .unwrap(),
            ScalarValue::Int64(None)
        );

        // 4. Untyped null default (ScalarValue::Null) preserves DataType::Null.
        let mut untyped_null_default = MatchRecognizeShiftEvaluator::new(
            false,
            LogicalAnchor::Last(0),
            1,
            ScalarValue::Null,
            NavigationKind::Prev,
            &DataType::Null,
        );
        let untyped_null_out = untyped_null_default
            .evaluate_all(&unmasked_values, 2)
            .unwrap();
        assert_eq!(untyped_null_out.data_type(), &DataType::Null);
        assert_eq!(untyped_null_out.len(), 2);
        assert_eq!(untyped_null_out.logical_null_count(), 2);
        assert_eq!(
            untyped_null_default
                .evaluate(&unmasked_values, &(0..2))
                .unwrap(),
            ScalarValue::Null
        );
    }

    #[test]
    fn unmasked_shift_handles_offsets_above_i64_max() {
        let unmasked_values: Vec<ArrayRef> =
            vec![Arc::new(Int32Array::from(vec![10, 20, 30]))];
        let masked_values: Vec<ArrayRef> = vec![
            Arc::clone(&unmasked_values[0]),
            Arc::new(BooleanArray::from(vec![true, true, true])),
        ];

        let mut offsets = vec![usize::MAX];
        #[cfg(target_pointer_width = "64")]
        offsets.push(i64::MAX as usize + 1);

        for offset in offsets {
            for default in [Some(-7), None] {
                for kind in [NavigationKind::Prev, NavigationKind::Next] {
                    let mut unmasked = MatchRecognizeShiftEvaluator::new(
                        false,
                        LogicalAnchor::Last(0),
                        offset,
                        ScalarValue::Int32(default),
                        kind,
                        &DataType::Int32,
                    );
                    let unmasked_out =
                        unmasked.evaluate_all(&unmasked_values, 3).unwrap();
                    let unmasked_arr =
                        unmasked_out.as_any().downcast_ref::<Int32Array>().unwrap();
                    assert_eq!(
                        unmasked_arr,
                        &Int32Array::from(vec![default; 3]),
                        "unmasked {kind:?} offset={offset}"
                    );

                    // Matches bounded evaluate() and masked evaluate_all().
                    for row in 0..3 {
                        let range = unmasked.get_range(row, 3).unwrap();
                        assert_eq!(
                            unmasked.evaluate(&unmasked_values, &range).unwrap(),
                            ScalarValue::Int32(default),
                            "bounded {kind:?} offset={offset} row={row}"
                        );
                    }

                    let mut masked = MatchRecognizeShiftEvaluator::new(
                        true,
                        LogicalAnchor::Last(0),
                        offset,
                        ScalarValue::Int32(default),
                        kind,
                        &DataType::Int32,
                    );
                    let masked_out = masked.evaluate_all(&masked_values, 3).unwrap();
                    assert_eq!(
                        masked_out.as_any().downcast_ref::<Int32Array>().unwrap(),
                        unmasked_arr,
                        "masked {kind:?} offset={offset}"
                    );
                }
            }
        }
    }

    #[test]
    fn bounded_evaluate_caches_uncoerced_default_and_preserves_cast_errors() {
        let values: Vec<ArrayRef> = vec![Arc::new(Int32Array::from(vec![10, 20, 30]))];

        // Uncoerced Int64(0) default against Int32 values for PREV(x, 1, 0).
        let mut prev = MatchRecognizeShiftEvaluator::new(
            false,
            LogicalAnchor::Last(0),
            1,
            ScalarValue::Int64(Some(0)),
            NavigationKind::Prev,
            &DataType::Int32,
        );
        assert!(prev.resolved_default.is_none());
        assert_eq!(
            prev.evaluate(&values, &(0..1)).unwrap(),
            ScalarValue::Int32(Some(0))
        );
        assert_eq!(
            prev.resolved_default,
            Some((DataType::Int32, ScalarValue::Int32(Some(0))))
        );
        assert_eq!(
            prev.evaluate(&values, &(0..2)).unwrap(),
            ScalarValue::Int32(Some(10))
        );
        assert_eq!(
            prev.evaluate(&values, &(1..3)).unwrap(),
            ScalarValue::Int32(Some(20))
        );

        // Uncoerced Int64(0) default against Int32 values for NEXT(x, 1, 0).
        let mut next = MatchRecognizeShiftEvaluator::new(
            false,
            LogicalAnchor::Last(0),
            1,
            ScalarValue::Int64(Some(0)),
            NavigationKind::Next,
            &DataType::Int32,
        );
        assert_eq!(
            next.evaluate(&values, &(0..2)).unwrap(),
            ScalarValue::Int32(Some(20))
        );
        assert_eq!(
            next.resolved_default,
            Some((DataType::Int32, ScalarValue::Int32(Some(0))))
        );
        assert_eq!(
            next.evaluate(&values, &(2..3)).unwrap(),
            ScalarValue::Int32(Some(0))
        );

        // Uncastable default must still fail immediately even when the row is in-range
        // and does not return the default.
        let mut invalid = MatchRecognizeShiftEvaluator::new(
            false,
            LogicalAnchor::Last(0),
            1,
            ScalarValue::Utf8(Some("not_an_int".to_string())),
            NavigationKind::Prev,
            &DataType::Int32,
        );
        let err = invalid.evaluate(&values, &(0..2)).unwrap_err();
        assert!(
            err.to_string().contains(
                "failed to cast MATCH_RECOGNIZE navigation default from Utf8 to Int32"
            ),
            "{err}"
        );
        assert!(invalid.resolved_default.is_none());
    }
}