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
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
// 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 helpers for PREV/NEXT aggregate arguments and default handling.

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

use datafusion::arrow::array::{
    Array, ArrayRef, BooleanArray, ListArray, UInt64Array, make_array, new_empty_array,
    new_null_array,
};
use datafusion::arrow::compute::{SortOptions, cast, take};
use datafusion::arrow::datatypes::{DataType, FieldRef, Schema};
use datafusion::arrow::row::{RowConverter, Rows, SortField};
use datafusion::common::cast::{as_boolean_array, as_list_array};
use datafusion::common::{DataFusionError, Result, ScalarValue, internal_err};
use datafusion::physical_expr_common::physical_expr::PhysicalExpr;
use datafusion::physical_expr_common::sort_expr::PhysicalSortExpr;
use datafusion_hash_grouped_order::gather::interleave_compact;

use crate::execution::storage::{canonical_interleave_type, retype_gather_data};
use crate::functions::navigation_common::{
    LogicalAnchor, NavigationKind, extract_bool_from_exprs,
    extract_logical_offset_from_exprs, nullable_navigation_data_type,
};
pub(crate) use crate::functions::navigation_common::{
    extract_default_from_exprs, extract_offset_from_exprs,
};

impl LogicalAnchor {
    /// Resolve a zero-based offset among matching rows to its index in the full row sequence.
    #[inline]
    pub(super) fn resolve_masked(
        &self,
        len: usize,
        mut is_matched: impl FnMut(usize) -> bool,
    ) -> Option<usize> {
        match *self {
            Self::First(offset) => (0..len).filter(|&i| is_matched(i)).nth(offset),
            Self::Last(offset) => (0..len).rev().filter(|&i| is_matched(i)).nth(offset),
        }
    }
}

/// Histories span batches, so their dictionaries must not retain batch-local key
/// capacity. Decode dictionaries and widen run ends recursively, preserving
/// nested field metadata and nullability.
/// The selected result is cast back to the aggregate's declared return type.
pub(crate) fn state_history_data_type(data_type: &DataType) -> DataType {
    let field = |field: &FieldRef| {
        Arc::new(
            field
                .as_ref()
                .clone()
                .with_data_type(state_history_data_type(field.data_type())),
        )
    };
    match data_type {
        DataType::Dictionary(_, value) => state_history_data_type(value),
        DataType::Struct(fields) => DataType::Struct(fields.iter().map(field).collect()),
        DataType::List(item) => DataType::List(field(item)),
        DataType::LargeList(item) => DataType::LargeList(field(item)),
        DataType::ListView(item) => DataType::ListView(field(item)),
        DataType::LargeListView(item) => DataType::LargeListView(field(item)),
        DataType::FixedSizeList(item, size) => {
            DataType::FixedSizeList(field(item), *size)
        }
        DataType::Map(entries, sorted) => DataType::Map(field(entries), *sorted),
        DataType::Union(fields, mode) => DataType::Union(
            fields.iter().map(|(id, item)| (id, field(item))).collect(),
            *mode,
        ),
        DataType::RunEndEncoded(ends, values) => DataType::RunEndEncoded(
            Arc::new(ends.as_ref().clone().with_data_type(DataType::Int64)),
            field(values),
        ),
        _ => data_type.clone(),
    }
}

pub(crate) fn normalize_state_history_array(
    array: &ArrayRef,
    target: &DataType,
) -> Result<ArrayRef> {
    if array.data_type() == target {
        return Ok(Arc::clone(array));
    }
    // Arrow's cast rebuilds REE children with canonical field names and
    // metadata, so container casts (such as Struct<REE>) must cast to the
    // canonical REE target before restoring declared child fields.
    let canonical_target = canonical_interleave_type(target)?;
    let error = match cast(array, &canonical_target) {
        Ok(array) => {
            return Ok(make_array(retype_gather_data(
                array.to_data(),
                target,
                false,
            )?));
        }
        Err(error) => error,
    };
    let source_history = state_history_data_type(array.data_type());
    let target_history = state_history_data_type(target);
    if source_history != target_history
        && nullable_navigation_data_type(&source_history) != target_history
    {
        return Err(error.into());
    }
    if array.is_empty() {
        return Ok(new_empty_array(target));
    }

    // Arrow can decode any dictionary, but cannot pack Boolean or arbitrary
    // nested values. Preserve those existing navigation result types through
    // DataFusion's scalar dictionary constructor when the cast is unavailable.
    if let DataType::Dictionary(key, value) = target {
        let values = normalize_state_history_array(array, value)?;
        let mut distinct = HashMap::new();
        let mut unique = Vec::new();
        let indices = (0..values.len())
            .map(|index| {
                let value = ScalarValue::try_from_array(&values, index)?;
                if value.is_null() {
                    return Ok(None);
                }
                let next = unique.len() as u64;
                let index = *distinct.entry(value.clone()).or_insert_with(|| {
                    unique.push(ScalarValue::Dictionary(key.clone(), Box::new(value)));
                    next
                });
                Ok(Some(index))
            })
            .collect::<Result<Vec<_>>>()?;
        if unique.is_empty() {
            return Ok(new_null_array(target, values.len()));
        }
        // Only distinct non-null values consume the dictionary's key capacity.
        let dictionary = ScalarValue::iter_to_array(unique)?;
        return Ok(take(
            dictionary.as_ref(),
            &UInt64Array::from(indices),
            None,
        )?);
    }
    let target_data = new_empty_array(target).to_data();
    if target_data.child_data().is_empty()
        || array.to_data().child_data().len() != target_data.child_data().len()
    {
        return Err(error.into());
    }
    // Compact sliced containers before rebuilding their children, so unused
    // history rows cannot exhaust a selected result's dictionary key capacity.
    let indices: Vec<_> = (0..array.len()).map(|index| (0, index)).collect();
    let selected = interleave_compact(&[array.as_ref()], &indices)?.to_data();
    let children = selected
        .child_data()
        .iter()
        .zip(target_data.child_data())
        .map(|(child, target)| {
            normalize_state_history_array(&make_array(child.clone()), target.data_type())
                .map(|array| array.to_data())
        })
        .collect::<Result<Vec<_>>>()?;
    Ok(make_array(
        selected
            .into_builder()
            .data_type(target.clone())
            .child_data(children)
            .build()?,
    ))
}

#[derive(Debug)]
pub(crate) struct NavigationArgs {
    pub(crate) anchor: LogicalAnchor,
    pub(crate) offset: usize,
    pub(crate) default_value: ScalarValue,
    pub(crate) fixed_arg_count: usize,
}

pub(crate) const EDGE_OFFSET_UDAF_ARG_COUNT: usize = 2;
pub(crate) const NAVIGATION_UDAF_ARG_COUNT: usize = 5;
pub(crate) const COMPOUND_NAVIGATION_UDAF_ARG_COUNT: usize = 7;

pub(crate) const fn base_state_fields(kind: NavigationKind) -> usize {
    if kind.is_shift() { 2 } else { 1 }
}

#[derive(Debug, Clone)]
pub(crate) struct NavigationOrderingSpec {
    pub(crate) data_type: DataType,
    pub(crate) options: SortOptions,
}

/// Ordering specification and Arrow row encoder for `ORDER BY`-sensitive navigation state.
#[derive(Debug)]
pub(crate) struct NavigationOrdering {
    data_types: Vec<DataType>,
    converter: RowConverter,
}

impl NavigationOrdering {
    pub(crate) fn from_sort_exprs(
        order_bys: &[PhysicalSortExpr],
        schema: &Schema,
    ) -> Result<Option<Self>> {
        if order_bys.is_empty() {
            return Ok(None);
        }
        let specs = order_bys
            .iter()
            .map(|sort_expr| {
                Ok(NavigationOrderingSpec {
                    data_type: sort_expr.expr.data_type(schema)?,
                    options: sort_expr.options,
                })
            })
            .collect::<Result<Vec<_>>>()?;
        Self::try_new(specs).map(Some)
    }

    pub(crate) fn try_new(specs: Vec<NavigationOrderingSpec>) -> Result<Self> {
        debug_assert!(!specs.is_empty());
        let mut data_types = Vec::with_capacity(specs.len());
        let mut sort_fields = Vec::with_capacity(specs.len());
        for spec in specs {
            sort_fields.push(SortField::new_with_options(
                state_history_data_type(&spec.data_type),
                spec.options,
            ));
            data_types.push(spec.data_type);
        }
        let converter = RowConverter::new(sort_fields)?;
        Ok(Self {
            data_types,
            converter,
        })
    }

    pub(crate) fn num_columns(&self) -> usize {
        self.data_types.len()
    }

    pub(crate) fn data_types(&self) -> &[DataType] {
        &self.data_types
    }

    pub(crate) fn validate_columns(
        &self,
        columns: &[ArrayRef],
        expected_len: usize,
        fixed_arg_count: usize,
        context: &str,
    ) -> Result<()> {
        if columns.len() != self.data_types.len() {
            return internal_err!(
                "{context} expects {} ordering argument(s), got {}",
                self.data_types.len(),
                columns.len()
            );
        }
        for (idx, (column, expected_type)) in
            columns.iter().zip(&self.data_types).enumerate()
        {
            require_same_len(column, fixed_arg_count + idx, expected_len, context)?;
            if column.data_type() != expected_type {
                return internal_err!(
                    "{context} ordering argument {idx} has type {}, expected {expected_type}",
                    column.data_type()
                );
            }
        }
        Ok(())
    }

    pub(crate) fn empty_rows(&self) -> Rows {
        self.converter.empty_rows(0, 0)
    }

    pub(crate) fn convert_columns(&self, columns: &[ArrayRef]) -> Result<Rows> {
        let columns = self.normalize_columns(columns)?;
        Ok(self.converter.convert_columns(&columns)?)
    }

    pub(crate) fn append_rows(
        &self,
        rows: &mut Rows,
        columns: &[ArrayRef],
    ) -> Result<()> {
        let columns = self.normalize_columns(columns)?;
        Ok(self.converter.append(rows, &columns)?)
    }

    fn normalize_columns(&self, columns: &[ArrayRef]) -> Result<Vec<ArrayRef>> {
        columns
            .iter()
            .zip(&self.data_types)
            .map(|(array, data_type)| {
                normalize_state_history_array(array, &state_history_data_type(data_type))
            })
            .collect()
    }

    /// Heap bytes owned beyond `size_of::<NavigationOrdering>()`.
    pub(crate) fn heap_size(&self) -> usize {
        let data_types_heap = self.data_types.capacity() * size_of::<DataType>()
            + self
                .data_types
                .iter()
                .map(|dt| dt.size() - size_of_val(dt))
                .sum::<usize>();
        data_types_heap + (self.converter.size() - size_of_val(&self.converter))
    }
}

#[derive(Debug)]
pub(crate) struct NavigationBatchArgs<'a> {
    pub(crate) value_array: ArrayRef,
    pub(crate) batch_len: usize,
    pub(crate) symbol_mask: Option<ArrayRef>,
    pub(crate) ordering_arrays: &'a [ArrayRef],
}

pub(crate) fn validate_navigation_arg_count(
    kind: NavigationKind,
    actual: usize,
) -> Result<()> {
    match kind {
        NavigationKind::First | NavigationKind::Last => {
            if actual != EDGE_OFFSET_UDAF_ARG_COUNT {
                return Err(DataFusionError::Plan(format!(
                    "MATCH_RECOGNIZE logical navigation aggregate expects exactly {EDGE_OFFSET_UDAF_ARG_COUNT} internal arguments, got {actual}"
                )));
            }
        }
        NavigationKind::Prev | NavigationKind::Next => {
            if actual != NAVIGATION_UDAF_ARG_COUNT
                && actual != COMPOUND_NAVIGATION_UDAF_ARG_COUNT
            {
                return Err(DataFusionError::Plan(format!(
                    "MATCH_RECOGNIZE navigation aggregate expects {NAVIGATION_UDAF_ARG_COUNT} or {COMPOUND_NAVIGATION_UDAF_ARG_COUNT} internal arguments, got {actual}"
                )));
            }
        }
    }

    Ok(())
}

pub(crate) fn parse_navigation_args(
    kind: NavigationKind,
    exprs: &[Arc<dyn PhysicalExpr>],
) -> Result<NavigationArgs> {
    validate_navigation_arg_count(kind, exprs.len())?;

    match kind {
        NavigationKind::First => Ok(NavigationArgs {
            anchor: LogicalAnchor::First(extract_logical_offset_from_exprs(exprs, 1)?),
            offset: 0,
            default_value: ScalarValue::Null,
            fixed_arg_count: EDGE_OFFSET_UDAF_ARG_COUNT,
        }),
        NavigationKind::Last => Ok(NavigationArgs {
            anchor: LogicalAnchor::Last(extract_logical_offset_from_exprs(exprs, 1)?),
            offset: 0,
            default_value: ScalarValue::Null,
            fixed_arg_count: EDGE_OFFSET_UDAF_ARG_COUNT,
        }),
        NavigationKind::Prev | NavigationKind::Next => {
            let anchor = if exprs.len() == COMPOUND_NAVIGATION_UDAF_ARG_COUNT {
                let is_first = extract_bool_from_exprs(exprs, 5)?;
                let logical_offset = extract_logical_offset_from_exprs(exprs, 6)?;
                if is_first {
                    LogicalAnchor::First(logical_offset)
                } else {
                    LogicalAnchor::Last(logical_offset)
                }
            } else {
                LogicalAnchor::Last(0)
            };
            Ok(NavigationArgs {
                anchor,
                offset: extract_offset_from_exprs(exprs, 1)?,
                default_value: extract_default_from_exprs(exprs, 2)?,
                fixed_arg_count: exprs.len(),
            })
        }
    }
}

/// Decode the Arrow batch arguments common to package-owned navigation accumulators.
///
/// For `FIRST`/`LAST` offset aggregates, planning supplies two fixed arguments
/// (`expr`, `logical_offset`) and uses SQL `FILTER` for row selection.
/// For `PREV`/`NEXT`, planning supplies five fixed arguments (`expr`, `offset`,
/// `default`, `is_matched`, `classifier_mask`) or seven fixed arguments for
/// compound `PREV`/`NEXT(FIRST/LAST(...))` (`..., logical_is_first, logical_offset`).
/// Any `ORDER BY` expressions follow the fixed arguments.
///
/// When `values[0]` arrives as an uncoerced `NullArray` (`DataType::Null`) while
/// `target_data_type` is concrete (for example, `PREV(NULL, 1, 42)` invoked without
/// DataFusion's logical `coerce_types` pass), `value_array` is normalized to a typed
/// null array of `target_data_type`.
pub(crate) fn decode_navigation_batch_args<'a>(
    kind: NavigationKind,
    fixed_arg_count: usize,
    target_data_type: &DataType,
    values: &'a [ArrayRef],
    ordering: Option<&NavigationOrdering>,
    context: &str,
) -> Result<NavigationBatchArgs<'a>> {
    let raw_value_array = require_navigation_value(values, 0, context)?;
    let batch_len = raw_value_array.len();

    let symbol_mask = if kind.is_shift() {
        let classifier = require_navigation_value(values, 4, context)?;
        let expand = classifier.len() == 1 && batch_len != 1;
        if !expand {
            require_same_len(classifier, 4, batch_len, context)?;
        }
        let mask = require_boolean_mask(classifier, 4, context)?;
        let symbol_mask = if expand {
            let scalar = mask.is_valid(0).then(|| mask.value(0));
            ScalarValue::Boolean(scalar).to_array_of_size(batch_len)?
        } else {
            Arc::clone(classifier)
        };
        Some(symbol_mask)
    } else {
        None
    };

    if values.len() < fixed_arg_count {
        return internal_err!(
            "{context} expects at least {fixed_arg_count} arguments, got {}",
            values.len()
        );
    }

    let ordering_arrays = &values[fixed_arg_count..];
    if let Some(ordering) = ordering {
        ordering.validate_columns(
            ordering_arrays,
            batch_len,
            fixed_arg_count,
            context,
        )?;
    } else if !ordering_arrays.is_empty() {
        return internal_err!(
            "{context} expects {fixed_arg_count} arguments without ORDER BY, got {}",
            values.len()
        );
    }

    let value_array =
        if raw_value_array.data_type().is_null() && !target_data_type.is_null() {
            new_null_array(target_data_type, batch_len)
        } else {
            Arc::clone(raw_value_array)
        };

    Ok(NavigationBatchArgs {
        value_array,
        batch_len,
        symbol_mask,
        ordering_arrays,
    })
}

/// Decoded and validated state `ListArray`s for `merge_batch` in both
/// single-group and grouped navigation accumulators.
#[derive(Debug)]
pub(crate) struct NavigationStateLists<'a> {
    pub(crate) values: &'a ListArray,
    pub(crate) symbols: Option<&'a ListArray>,
    pub(crate) orderings: Vec<&'a ListArray>,
}

impl<'a> NavigationStateLists<'a> {
    /// Decode and validate navigation state arrays for `merge_batch`.
    ///
    /// When `expected_len` is `Some(n)`, every state array must have length `n`;
    /// otherwise all state arrays must match `states[0].len()`.
    pub(crate) fn decode(
        states: &'a [ArrayRef],
        kind: NavigationKind,
        data_type: &DataType,
        ordering: Option<&NavigationOrdering>,
        expected_len: Option<usize>,
    ) -> Result<Self> {
        let base_fields = base_state_fields(kind);
        let ordering_count = ordering.map_or(0, NavigationOrdering::num_columns);
        let expected_columns = base_fields + ordering_count;
        if states.len() != expected_columns {
            return internal_err!(
                "navigation aggregate state expects {expected_columns} array(s), got {}",
                states.len()
            );
        }
        let expected_rows = expected_len.unwrap_or_else(|| states[0].len());
        if states.iter().any(|array| array.len() != expected_rows) {
            return internal_err!(
                "navigation aggregate state arrays have different row counts"
            );
        }

        let values = as_list_array(states[0].as_ref())?;
        let symbols = if kind.is_shift() {
            Some(as_list_array(states[1].as_ref())?)
        } else {
            None
        };
        let orderings = states[base_fields..]
            .iter()
            .map(|array| as_list_array(array.as_ref()))
            .collect::<Result<Vec<_>>>()?;

        if values.values().data_type() != &state_history_data_type(data_type)
            || symbols.is_some_and(|s| s.values().data_type() != &DataType::Boolean)
        {
            return internal_err!(
                "unexpected navigation aggregate state list element type"
            );
        }
        if let Some(ordering) = ordering {
            for (list, expected_type) in orderings.iter().zip(ordering.data_types()) {
                if list.values().data_type() != &state_history_data_type(expected_type) {
                    return internal_err!(
                        "unexpected navigation aggregate ordering state element type: expected {expected_type}, got {}",
                        list.values().data_type()
                    );
                }
            }
        }

        Ok(Self {
            values,
            symbols,
            orderings,
        })
    }

    /// Return `Ok(false)` when `row` has a null value list, `Ok(true)` when
    /// values, optional masks, and all ordering lists are non-null, or an
    /// internal error if values are present while masks or orderings are null.
    pub(crate) fn row_is_present(&self, row: usize) -> Result<bool> {
        if self.values.is_null(row) {
            return Ok(false);
        }
        if self.symbols.is_some_and(|s| s.is_null(row)) {
            return internal_err!(
                "navigation aggregate state masks cannot be null when values are present"
            );
        }
        if self.orderings.iter().any(|list| list.is_null(row)) {
            return internal_err!(
                "navigation aggregate state orderings cannot be null when values are present"
            );
        }
        Ok(true)
    }

    /// Extract and validate matching row-slice lengths for a non-null `row`.
    pub(crate) fn row_slices(
        &self,
        row: usize,
    ) -> Result<(ArrayRef, Option<ArrayRef>, Vec<ArrayRef>)> {
        let values = self.values.value(row);
        let symbols = self.symbols.map(|s| s.value(row));
        if let Some(ref symbols) = symbols
            && values.len() != symbols.len()
        {
            return internal_err!("navigation values and mask state lengths differ");
        }
        let orderings: Vec<ArrayRef> =
            self.orderings.iter().map(|list| list.value(row)).collect();
        if orderings.iter().any(|col| col.len() != values.len()) {
            return internal_err!("navigation values and ordering state lengths differ");
        }
        Ok((values, symbols, orderings))
    }
}

fn require_navigation_value<'a>(
    values: &'a [ArrayRef],
    index: usize,
    context: &str,
) -> Result<&'a ArrayRef> {
    values.get(index).ok_or_else(|| {
        DataFusionError::Internal(format!(
            "{context} expects argument {index}, got {} argument(s)",
            values.len()
        ))
    })
}

fn require_same_len(
    array: &ArrayRef,
    index: usize,
    expected_len: usize,
    context: &str,
) -> Result<()> {
    if array.len() != expected_len {
        return Err(DataFusionError::Internal(format!(
            "{context} argument {index} has length {}, expected {expected_len}",
            array.len()
        )));
    }

    Ok(())
}

fn require_boolean_mask<'a>(
    array: &'a ArrayRef,
    index: usize,
    context: &str,
) -> Result<&'a BooleanArray> {
    as_boolean_array(array.as_ref()).map_err(|err| {
        err.context(format!("{context} argument {index} must be a BooleanArray"))
    })
}

pub(crate) fn last_true_index(mask: &BooleanArray) -> Option<usize> {
    (0..mask.len())
        .rev()
        .find(|&idx| mask.is_valid(idx) && mask.value(idx))
}

pub(crate) fn evaluate_navigation_target(
    kind: NavigationKind,
    last_idx: Option<usize>,
    offset: usize,
    total_rows: usize,
    default_value: &ScalarValue,
    get_value: impl FnOnce(usize) -> Result<ScalarValue>,
) -> Result<ScalarValue> {
    match last_idx.and_then(|idx| kind.checked_target(idx, offset, total_rows)) {
        Some(target) => get_value(target),
        None => Ok(default_value.clone()),
    }
}

#[cfg(test)]
mod tests {
    use datafusion::arrow::array::{Int32Array, Int64Array};
    use datafusion::physical_expr::expressions::Literal;

    use super::*;

    fn qualified_values(symbol: ArrayRef) -> Vec<ArrayRef> {
        vec![
            Arc::new(Int32Array::from(vec![1, 2])),
            Arc::new(Int64Array::from(vec![1, 1])),
            Arc::new(Int32Array::from(vec![None, None])),
            Arc::new(BooleanArray::from(vec![true, true])),
            symbol,
        ]
    }

    #[test]
    fn navigation_construction_requires_the_internal_mask() {
        let mut exprs: Vec<Arc<dyn PhysicalExpr>> = [
            ScalarValue::Int32(Some(1)),
            ScalarValue::UInt64(Some(2)),
            ScalarValue::Int32(Some(9)),
            ScalarValue::Boolean(Some(true)),
        ]
        .into_iter()
        .map(|value| Arc::new(Literal::new(value)) as Arc<dyn PhysicalExpr>)
        .collect();
        assert!(
            parse_navigation_args(NavigationKind::Prev, &exprs)
                .unwrap_err()
                .to_string()
                .contains("expects 5 or 7 internal arguments")
        );
        exprs.push(Arc::new(Literal::new(ScalarValue::Boolean(Some(true)))));
        let args = parse_navigation_args(NavigationKind::Prev, &exprs).unwrap();
        assert_eq!(args.offset, 2);
        assert_eq!(args.default_value, ScalarValue::Int32(Some(9)));
        assert_eq!(args.anchor, LogicalAnchor::Last(0));
        assert_eq!(args.fixed_arg_count, 5);

        exprs.push(Arc::new(Literal::new(ScalarValue::Boolean(Some(true)))));
        exprs.push(Arc::new(Literal::new(ScalarValue::UInt64(Some(3)))));
        let compound = parse_navigation_args(NavigationKind::Prev, &exprs).unwrap();
        assert_eq!(compound.anchor, LogicalAnchor::First(3));
        assert_eq!(compound.fixed_arg_count, 7);

        let edge_exprs: Vec<Arc<dyn PhysicalExpr>> = vec![
            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
            Arc::new(Literal::new(ScalarValue::UInt64(Some(2)))),
        ];
        let edge = parse_navigation_args(NavigationKind::First, &edge_exprs).unwrap();
        assert_eq!(edge.anchor, LogicalAnchor::First(2));
        assert_eq!(edge.fixed_arg_count, 2);
    }

    #[test]
    fn navigation_decoder_reuses_classifier_mask_and_expands_scalar_masks() {
        let values = qualified_values(Arc::new(BooleanArray::from(vec![true, false])));
        let args = decode_navigation_batch_args(
            NavigationKind::Prev,
            NAVIGATION_UDAF_ARG_COUNT,
            &DataType::Int32,
            &values,
            None,
            "__mr_prev_agg",
        )
        .unwrap();
        assert_eq!(args.batch_len, 2);
        assert!(Arc::ptr_eq(&args.value_array, &values[0]));
        assert!(Arc::ptr_eq(args.symbol_mask.as_ref().unwrap(), &values[4]));
        assert!(args.ordering_arrays.is_empty());

        for scalar in [Some(true), Some(false), None] {
            let values = qualified_values(Arc::new(BooleanArray::from(vec![scalar])));
            let args = decode_navigation_batch_args(
                NavigationKind::Prev,
                NAVIGATION_UDAF_ARG_COUNT,
                &DataType::Int32,
                &values,
                None,
                "__mr_prev_agg",
            )
            .unwrap();
            assert_eq!(args.batch_len, 2);
            assert_eq!(
                as_boolean_array(args.symbol_mask.as_ref().unwrap().as_ref()).unwrap(),
                &BooleanArray::from(vec![scalar, scalar])
            );
            assert!(args.ordering_arrays.is_empty());
        }
    }

    #[test]
    fn navigation_decoder_normalizes_uncoerced_null_array_to_target_type() {
        use datafusion::arrow::array::NullArray;

        let values: Vec<ArrayRef> = vec![
            Arc::new(NullArray::new(3)),
            Arc::new(Int64Array::from(vec![1, 1, 1])),
            Arc::new(Int64Array::from(vec![42, 42, 42])),
            Arc::new(BooleanArray::from(vec![true, true, true])),
            Arc::new(BooleanArray::from(vec![false, true, true])),
        ];

        let normalized = decode_navigation_batch_args(
            NavigationKind::Prev,
            NAVIGATION_UDAF_ARG_COUNT,
            &DataType::Int64,
            &values,
            None,
            "__mr_prev_agg",
        )
        .unwrap();
        assert_eq!(normalized.batch_len, 3);
        assert_eq!(
            normalized
                .value_array
                .as_any()
                .downcast_ref::<Int64Array>()
                .unwrap(),
            &Int64Array::from(vec![None, None, None])
        );

        let preserved_null = decode_navigation_batch_args(
            NavigationKind::Prev,
            NAVIGATION_UDAF_ARG_COUNT,
            &DataType::Null,
            &values,
            None,
            "__mr_prev_agg",
        )
        .unwrap();
        assert!(Arc::ptr_eq(&preserved_null.value_array, &values[0]));
    }

    #[test]
    fn navigation_decoder_reports_argument_shape_type_and_length() {
        let ordinary = qualified_values(Arc::new(BooleanArray::from(vec![true, false])));
        let mut wrong_symbol_type = ordinary.clone();
        wrong_symbol_type[4] = ordinary[0].clone();
        let mut unexpected_extra = ordinary.clone();
        unexpected_extra.push(Arc::new(Int64Array::from(vec![1, 2])));
        for (values, diagnostic) in [
            (ordinary[..1].to_vec(), "expects argument 4"),
            (ordinary[..4].to_vec(), "expects argument 4"),
            (wrong_symbol_type, "argument 4 must be a BooleanArray"),
            (
                qualified_values(Arc::new(BooleanArray::from(vec![true, false, true]))),
                "argument 4 has length 3, expected 2",
            ),
            (
                unexpected_extra,
                "expects 5 arguments without ORDER BY, got 6",
            ),
        ] {
            let error = decode_navigation_batch_args(
                NavigationKind::Prev,
                NAVIGATION_UDAF_ARG_COUNT,
                &DataType::Int32,
                &values,
                None,
                "__mr_prev_agg",
            )
            .unwrap_err()
            .to_string();
            assert!(
                error.contains("__mr_prev_agg") && error.contains(diagnostic),
                "{error}"
            );
        }
    }

    #[test]
    fn navigation_decoder_validates_ordering_arguments() {
        let ordering = NavigationOrdering::try_new(vec![NavigationOrderingSpec {
            data_type: DataType::Int64,
            options: SortOptions::new(false, false),
        }])
        .unwrap();
        let base = qualified_values(Arc::new(BooleanArray::from(vec![true, false])));

        let mut valid = base.clone();
        valid.push(Arc::new(Int64Array::from(vec![10, 20])));
        let decoded = decode_navigation_batch_args(
            NavigationKind::Prev,
            NAVIGATION_UDAF_ARG_COUNT,
            &DataType::Int32,
            &valid,
            Some(&ordering),
            "__mr_prev_agg",
        )
        .unwrap();
        assert_eq!(decoded.ordering_arrays.len(), 1);
        assert!(Arc::ptr_eq(&decoded.ordering_arrays[0], &valid[5]));

        let mut wrong_len = base.clone();
        wrong_len.push(Arc::new(Int64Array::from(vec![10])));
        let mut wrong_type = base.clone();
        wrong_type.push(Arc::new(Int32Array::from(vec![10, 20])));
        for (values, diagnostic) in [
            (base, "expects 1 ordering argument(s), got 0"),
            (wrong_len, "argument 5 has length 1, expected 2"),
            (
                wrong_type,
                "ordering argument 0 has type Int32, expected Int64",
            ),
        ] {
            let error = decode_navigation_batch_args(
                NavigationKind::Prev,
                NAVIGATION_UDAF_ARG_COUNT,
                &DataType::Int32,
                &values,
                Some(&ordering),
                "__mr_prev_agg",
            )
            .unwrap_err()
            .to_string();
            assert!(
                error.contains("__mr_prev_agg") && error.contains(diagnostic),
                "{error}"
            );
        }
    }

    #[test]
    fn normalize_state_history_widens_non_nullable_ree_in_nested_dict_and_union() {
        use datafusion::arrow::array::{
            DictionaryArray, Int8Array, Int16Array, Int32Array, RunArray, UnionArray,
        };
        use datafusion::arrow::datatypes::{
            Field, Int8Type, Int16Type, Int32Type, UnionFields,
        };

        // 1. Dictionary(Int8, Dictionary(Int16, REE(Int32, Int32 non-null))) -> widened nullable REE.
        let run_ends = Int32Array::from(vec![1, 2]);
        let run_vals = Int32Array::from(vec![10, 20]);
        let ree: ArrayRef = Arc::new(
            RunArray::<Int32Type>::try_new(&run_ends, &run_vals).expect("valid REE"),
        );
        let inner_dict: ArrayRef = Arc::new(
            DictionaryArray::<Int16Type>::try_new(
                Int16Array::from(vec![0, 1]),
                Arc::clone(&ree),
            )
            .expect("valid inner dict"),
        );
        let outer_dict: ArrayRef = Arc::new(
            DictionaryArray::<Int8Type>::try_new(
                Int8Array::from(vec![0, 1]),
                Arc::clone(&inner_dict),
            )
            .expect("valid outer dict"),
        );
        let target_dict = nullable_navigation_data_type(outer_dict.data_type());
        let normalized = normalize_state_history_array(&outer_dict, &target_dict)
            .expect("nested dict with non-nullable REE should widen");
        assert_eq!(normalized.data_type(), &target_dict);
        assert_eq!(normalized.len(), 2);

        // 2. Union<0: REE(Int32, Int32 non-null)> -> state_history(nullable_navigation_data_type).
        let union_fields = UnionFields::try_new(
            vec![0_i8],
            vec![Field::new("r", ree.data_type().clone(), true)],
        )
        .expect("valid union fields");
        let union_arr: ArrayRef = Arc::new(
            UnionArray::try_new(
                union_fields,
                vec![0_i8, 0_i8].into(),
                None,
                vec![Arc::clone(&ree)],
            )
            .expect("valid union"),
        );
        let target_union = state_history_data_type(&nullable_navigation_data_type(
            union_arr.data_type(),
        ));
        let normalized = normalize_state_history_array(&union_arr, &target_union)
            .expect("union with non-nullable REE should widen");
        assert_eq!(normalized.data_type(), &target_union);
        assert_eq!(normalized.len(), 2);
    }
}