datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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
// 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 semantics and argument parsing for MATCH_RECOGNIZE navigation functions.
//!
//! Aggregate and window execution use different DataFusion interfaces, but
//! `FIRST`, `LAST`, `PREV`, and `NEXT` follow the same direction and offset
//! rules. This module defines those rules, checks target positions for both
//! `PREV` and `NEXT`, and parses their shared literal and default arguments.

use std::sync::Arc;

use datafusion::arrow::array::make_array;
use datafusion::arrow::datatypes::{DataType, Field, FieldRef};
use datafusion_common::{DataFusionError, Result, ScalarValue, exec_err};
use datafusion_physical_expr::expressions::Literal;
use datafusion_physical_expr_common::physical_expr::PhysicalExpr;

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

/// Arrow casts rebuild REE with canonical fields. Restore the requested field
/// names and metadata afterwards, widening required values only for SQL NULLs.
pub(crate) fn cast_navigation_scalar(
    value: &ScalarValue,
    target_type: &DataType,
) -> Result<ScalarValue> {
    if !contains_run_end_encoded(target_type) {
        return value.cast_to(target_type);
    }
    let canonical_type = canonical_interleave_type(target_type)?;
    let casted = value.cast_to(&canonical_type)?;
    let array = casted.to_array()?;
    let restored = make_array(retype_gather_data(array.to_data(), target_type, true)?);
    ScalarValue::try_from_array(restored.as_ref(), 0)
}

/// The closed MATCH_RECOGNIZE navigation family.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum NavigationKind {
    First,
    Last,
    Prev,
    Next,
}

impl NavigationKind {
    /// The source-level name registered for a window navigation function.
    pub(crate) const fn window_name(self) -> &'static str {
        match self {
            Self::First => "first",
            Self::Last => "last",
            Self::Prev => "prev",
            Self::Next => "next",
        }
    }

    /// The package-owned aggregate implementation name for this navigation function.
    pub(crate) const fn aggregate_name(self) -> &'static str {
        match self {
            Self::First => "__mr_first_agg",
            Self::Last => "__mr_last_agg",
            Self::Prev => "__mr_prev_agg",
            Self::Next => "__mr_next_agg",
        }
    }

    pub(crate) const fn is_edge(self) -> bool {
        matches!(self, Self::First | Self::Last)
    }

    pub(crate) const fn is_shift(self) -> bool {
        matches!(self, Self::Prev | Self::Next)
    }

    /// Resolve a PREV/NEXT target relative to `anchor`.
    ///
    /// Subtraction underflow, addition overflow, and targets outside the valid
    /// row range are all represented as `None`, which selects the function's
    /// configured default. Edge navigation does not have an offset target and
    /// therefore returns `None` if passed here.
    #[inline]
    pub(crate) fn checked_target(
        self,
        anchor: usize,
        offset: usize,
        upper_bound: usize,
    ) -> Option<usize> {
        let target = match self {
            Self::Prev => anchor.checked_sub(offset),
            Self::Next => anchor.checked_add(offset),
            Self::First | Self::Last => None,
        }?;
        (target < upper_bound).then_some(target)
    }

    pub(crate) const fn is_causal(self) -> bool {
        !matches!(self, Self::Next)
    }
}

/// Logical anchor within matched rows for `FIRST`/`LAST` offset navigation and
/// compound `PREV`/`NEXT(FIRST/LAST(...))` navigation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum LogicalAnchor {
    First(usize),
    Last(usize),
}

impl LogicalAnchor {
    pub(crate) const fn offset(self) -> usize {
        match self {
            Self::First(offset) | Self::Last(offset) => offset,
        }
    }

    /// Resolve a logical anchor directly against `len` already-filtered rows.
    #[inline]
    pub(crate) const fn resolve_unmasked(self, len: usize) -> Option<usize> {
        match self {
            Self::First(offset) => {
                if offset < len {
                    Some(offset)
                } else {
                    None
                }
            }
            Self::Last(offset) => match offset.checked_add(1) {
                Some(needed) => len.checked_sub(needed),
                None => None,
            },
        }
    }
}

/// Return the literal scalar value for `args[index]`, or `None` when absent.
pub(crate) fn get_scalar_value_from_args(
    args: &[Arc<dyn PhysicalExpr>],
    index: usize,
) -> Result<Option<ScalarValue>> {
    Ok(if let Some(field) = args.get(index) {
        let tmp = field
            .downcast_ref::<Literal>()
            .ok_or_else(|| {
                DataFusionError::NotImplemented(format!(
                    "MATCH_RECOGNIZE navigation argument {index} must be a literal"
                ))
            })?
            .value()
            .clone();
        Some(tmp)
    } else {
        None
    })
}

/// Convert a non-null integer scalar to a non-negative `usize`.
fn scalar_to_non_negative_usize(value: &ScalarValue, label: &str) -> Result<usize> {
    let non_negative = match value {
        ScalarValue::UInt8(Some(v)) => u64::from(*v),
        ScalarValue::UInt16(Some(v)) => u64::from(*v),
        ScalarValue::UInt32(Some(v)) => u64::from(*v),
        ScalarValue::UInt64(Some(v)) => *v,
        ScalarValue::Int8(Some(v)) => u64::try_from(*v).map_err(|_| {
            DataFusionError::Execution(format!("{label} must be non-negative"))
        })?,
        ScalarValue::Int16(Some(v)) => u64::try_from(*v).map_err(|_| {
            DataFusionError::Execution(format!("{label} must be non-negative"))
        })?,
        ScalarValue::Int32(Some(v)) => u64::try_from(*v).map_err(|_| {
            DataFusionError::Execution(format!("{label} must be non-negative"))
        })?,
        ScalarValue::Int64(Some(v)) => u64::try_from(*v).map_err(|_| {
            DataFusionError::Execution(format!("{label} must be non-negative"))
        })?,
        _ => return exec_err!("{label} must be an integer"),
    };

    usize::try_from(non_negative).map_err(|_| {
        DataFusionError::Execution(format!(
            "{label} {non_negative} cannot be represented as usize on this platform"
        ))
    })
}

/// Convert an offset to `usize`.
///
/// Null values default to `1`. Non-integer, negative, and out-of-range offsets
/// return an execution error.
pub(crate) fn scalar_to_usize(value: &ScalarValue) -> Result<usize> {
    if value.is_null() {
        return Ok(1);
    }

    scalar_to_non_negative_usize(value, "MATCH_RECOGNIZE navigation offset")
}

/// Extract a literal offset from physical-expression argument lists.
pub(crate) fn extract_offset_from_exprs(
    exprs: &[Arc<dyn PhysicalExpr>],
    idx: usize,
) -> Result<usize> {
    let Some(value) = get_scalar_value_from_args(exprs, idx)? else {
        return Ok(1);
    };
    scalar_to_usize(&value)
}

/// Extract a literal default value from physical-expression argument lists.
pub(crate) fn extract_default_from_exprs(
    exprs: &[Arc<dyn PhysicalExpr>],
    idx: usize,
) -> Result<ScalarValue> {
    Ok(get_scalar_value_from_args(exprs, idx)?.unwrap_or(ScalarValue::Null))
}

/// Convert a logical navigation offset (`FIRST`/`LAST`) to `usize`.
///
/// Unlike physical `PREV`/`NEXT` offsets, logical offsets must be non-null
/// non-negative integers.
pub(crate) fn scalar_to_logical_offset(value: &ScalarValue) -> Result<usize> {
    if value.is_null() {
        return exec_err!("MATCH_RECOGNIZE logical navigation offset cannot be NULL");
    }

    scalar_to_non_negative_usize(value, "MATCH_RECOGNIZE logical navigation offset")
}

/// Extract a required literal logical navigation offset from physical expressions.
pub(crate) fn extract_logical_offset_from_exprs(
    exprs: &[Arc<dyn PhysicalExpr>],
    idx: usize,
) -> Result<usize> {
    let Some(value) = get_scalar_value_from_args(exprs, idx)? else {
        return exec_err!(
            "MATCH_RECOGNIZE logical navigation offset argument {idx} is missing"
        );
    };
    scalar_to_logical_offset(&value)
}

/// Extract a required non-null Boolean literal from physical expressions.
pub(crate) fn extract_bool_from_exprs(
    exprs: &[Arc<dyn PhysicalExpr>],
    idx: usize,
) -> Result<bool> {
    match get_scalar_value_from_args(exprs, idx)? {
        Some(ScalarValue::Boolean(Some(value))) => Ok(value),
        _ => exec_err!(
            "MATCH_RECOGNIZE logical navigation anchor argument {idx} must be a non-null Boolean literal"
        ),
    }
}

/// Refine shift-navigation argument types (`PREV`/`NEXT`) when the value
/// argument (`arg_types[0]`) is untyped `DataType::Null` and the default
/// argument (`arg_types[2]`) has a concrete type.
///
/// Mirrors DataFusion's `LAG`/`LEAD` behavior (issue #12717): non-Null value
/// types remain exact (leaving default casting to the evaluator/accumulator),
/// while an untyped `Null` value expression takes the default's concrete type.
pub(crate) fn coerce_shift_navigation_types(arg_types: &[DataType]) -> Vec<DataType> {
    let mut coerced = arg_types.to_vec();
    if let (Some(value_type), Some(default_type)) = (arg_types.first(), arg_types.get(2))
        && value_type.is_null()
        && !default_type.is_null()
    {
        coerced[0] = default_type.clone();
    }
    coerced
}

/// REE has no outer validity bitmap, so nullable navigation results need
/// nullable encoded values even in partitions where every target exists.
/// Preserve custom fields recursively, including REE nested in containers.
pub(crate) fn nullable_navigation_data_type(data_type: &DataType) -> DataType {
    let field = |field: &FieldRef| {
        Arc::new(
            field
                .as_ref()
                .clone()
                .with_data_type(nullable_navigation_data_type(field.data_type())),
        )
    };
    match data_type {
        DataType::RunEndEncoded(ends, values) => DataType::RunEndEncoded(
            Arc::clone(ends),
            Arc::new(field(values).as_ref().clone().with_nullable(true)),
        ),
        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::Dictionary(keys, values) => DataType::Dictionary(
            keys.clone(),
            Box::new(nullable_navigation_data_type(values)),
        ),
        DataType::Union(fields, mode) => DataType::Union(
            fields.iter().map(|(id, item)| (id, field(item))).collect(),
            *mode,
        ),
        _ => data_type.clone(),
    }
}

/// Resolve the nullable output field for a navigation function (`FIRST`/`LAST`/`PREV`/`NEXT`).
///
/// For shift functions (`PREV`/`NEXT`), when `input_fields[0]` has
/// `DataType::Null` and a non-Null default field exists at `input_fields[2]`,
/// the output takes the default's type and metadata (matching DataFusion's
/// `LAG`/`LEAD` `parse_expr_field`). Otherwise it preserves `input_fields[0]`'s
/// type and Arrow metadata, widening encoded values to allow SQL NULLs.
pub(crate) fn navigation_return_field(
    kind: NavigationKind,
    input_fields: &[FieldRef],
    output_name: &str,
) -> FieldRef {
    let source = input_fields.first().map(|value_field| {
        if kind.is_shift()
            && value_field.data_type().is_null()
            && let Some(default_field) = input_fields.get(2)
            && !default_field.data_type().is_null()
        {
            default_field
        } else {
            value_field
        }
    });
    let field = match source {
        Some(field) => field
            .as_ref()
            .clone()
            .with_name(output_name)
            .with_data_type(nullable_navigation_data_type(field.data_type()))
            .with_nullable(true),
        None => Field::new(output_name, DataType::Null, true),
    };
    Arc::new(field)
}

/// Resolve a `PREV`/`NEXT` default scalar to `target_type`.
///
/// Untyped or typed `NULL` defaults become a typed null for `target_type`.
/// Non-null defaults are cast to `target_type` so accumulators and window
/// evaluators produce values matching the target column type; invalid casts
/// attach MATCH_RECOGNIZE navigation default context.
pub(crate) fn resolve_navigation_default(
    default_value: &ScalarValue,
    target_type: &DataType,
) -> Result<ScalarValue> {
    if default_value.is_null() {
        ScalarValue::try_from(target_type)
    } else {
        cast_navigation_scalar(default_value, target_type).map_err(|err| {
            let source_type = default_value.data_type();
            err.context(format!(
                "failed to cast MATCH_RECOGNIZE navigation default from {source_type} to {target_type}"
            ))
        })
    }
}

#[cfg(test)]
pub(crate) mod test_support {
    use std::collections::HashMap;
    use std::sync::Arc;

    use datafusion::arrow::array::{Array, ArrayRef, Int32Array, RunArray, make_array};
    use datafusion::arrow::compute::cast;
    use datafusion::arrow::datatypes::{DataType, Field, Int32Type};

    pub(crate) fn custom_run_array(nullable: bool) -> ArrayRef {
        let metadata = HashMap::from([("navigation".to_string(), "custom".to_string())]);
        let target = DataType::RunEndEncoded(
            Arc::new(
                Field::new("ends", DataType::Int32, false)
                    .with_metadata(metadata.clone()),
            ),
            Arc::new(
                Field::new("payload", DataType::Int32, nullable).with_metadata(metadata),
            ),
        );
        let array = RunArray::<Int32Type>::try_new(
            &Int32Array::from(vec![1, 2]),
            &Int32Array::from(vec![10, 20]),
        )
        .unwrap();
        make_array(
            array
                .to_data()
                .into_builder()
                .data_type(target)
                .build()
                .unwrap(),
        )
    }

    pub(crate) fn assert_run_values(array: &ArrayRef, expected: &[Option<i32>]) {
        let decoded = cast(array, &DataType::Int32).unwrap();
        assert_eq!(
            decoded.as_any().downcast_ref::<Int32Array>().unwrap(),
            &Int32Array::from(expected.to_vec())
        );
    }
}

#[cfg(test)]
mod tests {
    use datafusion::arrow::datatypes::DataType;
    use datafusion_common::ScalarValue;

    use super::{
        LogicalAnchor, NavigationKind, resolve_navigation_default,
        scalar_to_logical_offset, scalar_to_usize,
    };

    #[test]
    fn navigation_default_preserves_custom_run_fields() {
        use super::test_support::{assert_run_values, custom_run_array};

        for nullable in [false, true] {
            let input = custom_run_array(nullable);
            let default = resolve_navigation_default(
                &ScalarValue::Int32(Some(7)),
                input.data_type(),
            )
            .unwrap();
            assert_eq!(default.data_type(), *input.data_type());
            let selected = ScalarValue::try_from_array(&input, 0).unwrap();
            let result = ScalarValue::iter_to_array([default, selected]).unwrap();
            assert_eq!(result.data_type(), input.data_type());
            assert_run_values(&result, &[Some(7), Some(10)]);

            let null = resolve_navigation_default(&ScalarValue::Null, input.data_type())
                .unwrap();
            let result = null.to_array_of_size(2).unwrap();
            assert_eq!(null.data_type(), *input.data_type());
            assert_run_values(&result, &[None, None]);
        }
    }

    #[test]
    fn navigation_default_preserves_nested_custom_run_fields() {
        use super::test_support::custom_run_array;
        use datafusion::arrow::array::{Array, StructArray};
        use datafusion::arrow::datatypes::Field;
        use std::sync::Arc;

        let values = custom_run_array(false);
        let input = StructArray::new(
            vec![Arc::new(Field::new(
                "nested",
                values.data_type().clone(),
                true,
            ))]
            .into(),
            vec![values],
            None,
        );
        let scalar = ScalarValue::try_from_array(&input, 0).unwrap();
        let default = resolve_navigation_default(&scalar, input.data_type()).unwrap();
        assert_eq!(default.data_type(), *input.data_type());
        assert_eq!(default, scalar);
    }

    #[test]
    fn logical_anchor_resolves_unmasked_positions() {
        assert_eq!(LogicalAnchor::First(0).resolve_unmasked(3), Some(0));
        assert_eq!(LogicalAnchor::First(2).resolve_unmasked(3), Some(2));
        assert_eq!(LogicalAnchor::First(3).resolve_unmasked(3), None);
        assert_eq!(LogicalAnchor::First(0).resolve_unmasked(0), None);
        assert_eq!(LogicalAnchor::Last(0).resolve_unmasked(3), Some(2));
        assert_eq!(LogicalAnchor::Last(2).resolve_unmasked(3), Some(0));
        assert_eq!(LogicalAnchor::Last(3).resolve_unmasked(3), None);
        assert_eq!(LogicalAnchor::Last(usize::MAX).resolve_unmasked(3), None);
    }

    #[test]
    fn scalar_to_logical_offset_rejects_null_negative_and_non_integer() {
        assert_eq!(
            scalar_to_logical_offset(&ScalarValue::UInt64(Some(0))).unwrap(),
            0
        );
        assert_eq!(
            scalar_to_logical_offset(&ScalarValue::Int64(Some(4))).unwrap(),
            4
        );
        for null_val in [ScalarValue::Null, ScalarValue::Int64(None)] {
            let err = scalar_to_logical_offset(&null_val).unwrap_err();
            assert!(err.to_string().contains("cannot be NULL"), "{err}");
        }
        let neg = scalar_to_logical_offset(&ScalarValue::Int64(Some(-1))).unwrap_err();
        assert!(neg.to_string().contains("must be non-negative"), "{neg}");
        let non_int =
            scalar_to_logical_offset(&ScalarValue::Float64(Some(1.0))).unwrap_err();
        assert!(
            non_int.to_string().contains("must be an integer"),
            "{non_int}"
        );
    }

    #[test]
    fn checked_targets_reject_underflow_upper_bound_and_overflow() {
        for (kind, anchor, offset, bound) in [
            (NavigationKind::Prev, 0, 1, 5),
            (NavigationKind::Next, 4, 1, 5),
            (NavigationKind::Next, usize::MAX, 1, usize::MAX),
        ] {
            assert_eq!(kind.checked_target(anchor, offset, bound), None, "{kind:?}");
        }
    }

    #[test]
    fn scalar_to_usize_accepts_null_and_non_negative_integers() {
        assert_eq!(scalar_to_usize(&ScalarValue::Null).unwrap(), 1);
        assert_eq!(scalar_to_usize(&ScalarValue::Int64(None)).unwrap(), 1);
        assert_eq!(scalar_to_usize(&ScalarValue::Int8(Some(0))).unwrap(), 0);
        assert_eq!(scalar_to_usize(&ScalarValue::Int16(Some(1))).unwrap(), 1);
        assert_eq!(scalar_to_usize(&ScalarValue::Int32(Some(2))).unwrap(), 2);
        assert_eq!(scalar_to_usize(&ScalarValue::Int64(Some(0))).unwrap(), 0);
        assert_eq!(scalar_to_usize(&ScalarValue::UInt8(Some(3))).unwrap(), 3);
        assert_eq!(scalar_to_usize(&ScalarValue::UInt16(Some(4))).unwrap(), 4);
        assert_eq!(scalar_to_usize(&ScalarValue::UInt32(Some(5))).unwrap(), 5);
        assert_eq!(scalar_to_usize(&ScalarValue::UInt64(Some(3))).unwrap(), 3);
        #[cfg(target_pointer_width = "64")]
        {
            let above_i64_max = i64::MAX as u64 + 1;
            assert_eq!(
                scalar_to_usize(&ScalarValue::UInt64(Some(above_i64_max))).unwrap(),
                above_i64_max as usize
            );
            assert_eq!(
                scalar_to_logical_offset(&ScalarValue::UInt64(Some(above_i64_max)))
                    .unwrap(),
                above_i64_max as usize
            );
        }
    }

    #[test]
    fn scalar_to_usize_rejects_negative_and_non_integer_offsets() {
        for negative in [ScalarValue::Int64(Some(-1)), ScalarValue::Int32(Some(-5))] {
            let error = scalar_to_usize(&negative)
                .expect_err("negative navigation offsets must be rejected");
            assert!(
                error.to_string().contains("offset must be non-negative"),
                "{error}"
            );
        }
        for non_int in [
            ScalarValue::Utf8(Some("1".into())),
            ScalarValue::Float64(Some(1.5)),
            ScalarValue::Boolean(Some(true)),
        ] {
            let error = scalar_to_usize(&non_int)
                .expect_err("non-integer navigation offsets must be rejected");
            assert!(
                error.to_string().contains("offset must be an integer"),
                "{error}"
            );
        }
    }

    #[cfg(target_pointer_width = "32")]
    #[test]
    fn offset_must_fit_platform_row_index() {
        let error = scalar_to_usize(&ScalarValue::Int64(Some(i64::MAX)))
            .expect_err("i64::MAX must not truncate to a 32-bit row index");
        assert!(error.to_string().contains("cannot be represented as usize"));
    }

    #[test]
    fn resolve_navigation_default_maps_nulls_casts_and_reports_context() {
        assert_eq!(
            resolve_navigation_default(&ScalarValue::Null, &DataType::Int32).unwrap(),
            ScalarValue::Int32(None)
        );
        assert_eq!(
            resolve_navigation_default(&ScalarValue::Int64(None), &DataType::Int32)
                .unwrap(),
            ScalarValue::Int32(None)
        );
        assert_eq!(
            resolve_navigation_default(&ScalarValue::Null, &DataType::Null).unwrap(),
            ScalarValue::Null
        );
        assert_eq!(
            resolve_navigation_default(&ScalarValue::Int64(Some(0)), &DataType::Int32)
                .unwrap(),
            ScalarValue::Int32(Some(0))
        );
        assert_eq!(
            resolve_navigation_default(
                &ScalarValue::Utf8(Some("7".into())),
                &DataType::Int32,
            )
            .unwrap(),
            ScalarValue::Int32(Some(7))
        );

        let err = resolve_navigation_default(
            &ScalarValue::Utf8(Some("not-an-int".into())),
            &DataType::Int32,
        )
        .unwrap_err();
        assert!(
            err.to_string().contains(
                "failed to cast MATCH_RECOGNIZE navigation default from Utf8 to Int32"
            ),
            "{err}"
        );
    }
}