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

//! Decodes VM registers into values for generic physical-expression evaluation.
//!
//! The row loop normally runs predicates directly on registers and navigation
//! state. When generic physical-expression evaluation is needed, this module
//! fills temporary managed-aggregate value vectors from those VM structures.

use crate::core::AbsoluteRow;
pub(crate) use crate::core::vm::i128_from_words;
use crate::core::vm::{
    AggregateValueSource, NavigationLocation, NavigationSource, NavigationValueDomain,
    RegisterLayout, StateCellSource, temporal_scalar_from_bits,
};
use crate::execution::common::progress::CoarseWorkBatch;
use crate::execution::matching::program::validated_vm::{
    NavigationSlotId, PreviousBufferId, RegisterId,
};
use crate::execution::matching::row_loop::row_data::resolve_optional_column;
use crate::execution::matching::row_loop::statistical_state::VarianceState;
use crate::execution::matching::row_loop::types::{
    NavigationDatum, NavigationLookup, NavigationReadView,
};
use crate::execution::matching::{ResolvedInputColumn, WinningValue};
use crate::execution::storage::collection::BatchCollection;
use crate::planning::predicate::validate_decimal_scalar_value;
use datafusion::arrow::datatypes::{DataType, Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::scalar::ScalarValue;
use datafusion_common::{DataFusionError, Result};

#[inline]
pub(crate) fn register_average(sum: u64, count: u64) -> Option<f64> {
    (count != 0).then(|| f64::from_bits(sum) / count as f64)
}

#[inline]
pub(crate) fn register_decimal_average(
    sum: i128,
    count: u64,
    scale_factor: u32,
) -> Result<Option<i128>> {
    if count == 0 {
        return Ok(None);
    }
    let Some(scaled) = sum.checked_mul(i128::from(scale_factor)) else {
        return datafusion_common::exec_err!(
            "Decimal128 overflow while materializing VM AVG"
        );
    };
    Ok(Some(scaled / i128::from(count)))
}

/// Bound result descriptor for one managed aggregate.
///
/// The cell is shared by every result consumer. It owns the aggregate's output
/// type, SQL-empty-input rule, and checked state source so callers never infer
/// those semantics from raw register words independently.
#[derive(Debug, Clone)]
pub(crate) struct BoundStateCell {
    source: BoundStateSource,
    output_type: DataType,
    nonnull_count_slot: Option<RegisterId>,
}

impl BoundStateCell {
    #[inline]
    pub(crate) const fn source(&self) -> &BoundStateSource {
        &self.source
    }

    #[inline]
    pub(crate) const fn output_type(&self) -> &DataType {
        &self.output_type
    }

    #[inline]
    pub(crate) const fn nonnull_count_slot(&self) -> Option<RegisterId> {
        self.nonnull_count_slot
    }

    #[inline]
    pub(crate) fn has_no_nonnull_rows(&self, reg_slice: &[u64]) -> bool {
        self.nonnull_count_slot
            .is_some_and(|slot| reg_slice[slot.index()] == 0)
    }

    /// Decode a physically matched aggregate from the elected lane. A missing
    /// value here requests selected-row reduction, while a SQL NULL is a
    /// successfully forwarded typed scalar.
    pub(crate) fn winning_value(
        &self,
        registers: &[u64],
        output_type: &DataType,
    ) -> Option<WinningValue> {
        use datafusion::arrow::datatypes::{Decimal128Type, DecimalType};
        if self.output_type != *output_type {
            return None;
        }
        let valid = !self.has_no_nonnull_rows(registers);
        let value = match (&self.source, output_type) {
            (BoundStateSource::Register { slot }, DataType::Int32) => {
                WinningValue::Int32(valid.then(|| registers[slot.index()] as i32))
            }
            (BoundStateSource::Register { slot }, DataType::Int64) => {
                WinningValue::Int64(valid.then(|| registers[slot.index()] as i64))
            }
            (BoundStateSource::Register { slot }, DataType::Float64) => {
                WinningValue::Float64(
                    valid.then(|| f64::from_bits(registers[slot.index()])),
                )
            }
            (
                BoundStateSource::Avg {
                    sum_slot,
                    count_slot,
                },
                DataType::Float64,
            ) => {
                let count = registers[count_slot.index()];
                WinningValue::Float64(if valid {
                    register_average(registers[sum_slot.index()], count)
                } else {
                    None
                })
            }
            (BoundStateSource::RegisterD128 { slot }, DataType::Decimal128(..)) => {
                WinningValue::Decimal128(valid.then(|| {
                    i128_from_words(registers[slot.index()], registers[slot.index() + 1])
                }))
            }
            (
                BoundStateSource::AvgDecimal128 {
                    sum_slot,
                    count_slot,
                    scale_factor,
                },
                DataType::Decimal128(..),
            ) => {
                let count = registers[count_slot.index()];
                let value = if valid {
                    let sum = i128_from_words(
                        registers[sum_slot.index()],
                        registers[sum_slot.index() + 1],
                    );
                    register_decimal_average(sum, count, *scale_factor).ok()?
                } else {
                    None
                };
                WinningValue::Decimal128(value)
            }
            _ => return None,
        };
        match (value, output_type) {
            // The native grouped operator owns NaN payload selection and decimal overflow errors.
            (WinningValue::Float64(Some(v)), _) if v.is_nan() => None,
            (WinningValue::Decimal128(Some(v)), DataType::Decimal128(p, s))
                if Decimal128Type::validate_decimal_precision(v, *p, *s).is_err() =>
            {
                None
            }
            _ => Some(value),
        }
    }

    #[inline]
    pub(crate) const fn is_state_owned(&self) -> bool {
        !matches!(self.source, BoundStateSource::AccumulatorOwned)
    }
}

/// Result of reading a bound state cell.
///
/// SQL `NULL` is represented by `Scalar(typed_null)`. `AccumulatorOwned` means
/// no VM state exists and the caller must retain the accumulator's current
/// scratch value.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum BoundStateRead {
    Scalar(ScalarValue),
    AccumulatorOwned,
    CandidateStart(ResolvedInputColumn),
    RetainedRow {
        column: ResolvedInputColumn,
        row: AbsoluteRow,
    },
}

/// Candidate coordinates remain absolute across retained-input rebinding.
#[derive(Clone, Copy)]
pub(crate) struct CandidateInput<'a> {
    collection: &'a BatchCollection,
    start: AbsoluteRow,
    origin: usize,
}

impl<'a> CandidateInput<'a> {
    pub(crate) fn new(
        collection: &'a BatchCollection,
        start: AbsoluteRow,
        origin: usize,
    ) -> Self {
        Self {
            collection,
            start,
            origin,
        }
    }

    pub(crate) fn batch_row_at(
        self,
        target: AbsoluteRow,
    ) -> Result<(&'a RecordBatch, usize)> {
        // A live candidate's retention floor keeps every row from its start available.
        let row = usize::try_from(target.as_u64())
            .ok()
            .and_then(|row| row.checked_sub(self.origin))
            .filter(|&row| row < self.collection.num_rows())
            .ok_or_else(|| {
                DataFusionError::Internal(
                    "MATCH_RECOGNIZE retained candidate row is outside retained input"
                        .into(),
                )
            })?;
        let (batch, row) = self.collection.locate(row);
        Ok((self.collection.batch(batch), row))
    }

    pub(crate) fn batch_row(self) -> Result<(&'a RecordBatch, usize)> {
        self.batch_row_at(self.start)
    }

    pub(crate) fn scalar_at(
        self,
        column: ResolvedInputColumn,
        target: AbsoluteRow,
    ) -> Result<ScalarValue> {
        let (batch, row) = self.batch_row_at(target)?;
        ScalarValue::try_from_array(batch.column(column.index()), row)
    }

    pub(crate) fn scalar(self, column: ResolvedInputColumn) -> Result<ScalarValue> {
        self.scalar_at(column, self.start)
    }
}

/// Build the temporary-value decode plan from the validated register layout.
/// Recipes define state encodings; binding checks source ranges, schema columns,
/// output alignment and navigation defaults before execution.
pub(crate) fn bind_state_cells(
    schema: &Schema,
    register_layout: &RegisterLayout,
    aggregate_data_types: &[DataType],
) -> Result<Vec<BoundStateCell>> {
    let aggregate_count = aggregate_data_types.len();
    if register_layout.aggregates().len() != aggregate_count {
        return Err(DataFusionError::Internal(format!(
            "MATCH_RECOGNIZE VM scratch metadata is not aligned: aggregates={aggregate_count}, layouts={}",
            register_layout.aggregates().len()
        )));
    }

    aggregate_data_types
        .iter()
        .zip(register_layout.aggregates())
        .enumerate()
        .map(|(agg_idx, (data_type, aggregate))| {
            Ok(BoundStateCell {
                source: BoundStateSource::try_bind(
                    &aggregate.value_source,
                    data_type,
                    schema,
                    register_layout,
                    agg_idx,
                )?,
                output_type: data_type.clone(),
                // The layout constructor has already checked this allocation.
                nonnull_count_slot: aggregate
                    .nonnull_count_slot
                    .map(RegisterId::from_validated),
            })
        })
        .collect()
}

/// Materialize VM-owned cells only for fallback physical-expression evaluation.
/// Only register-only programs use this path; accumulator updates populate their
/// own scratch. Account each decode (including failures), retaining the decode
/// error if cancellation occurs at the same coarse boundary.
pub(crate) fn hydrate_fallback_aggregates(
    state_cells: &[BoundStateCell],
    registers: &[u64],
    nav_state: NavigationReadView<'_>,
    candidate_input: Option<CandidateInput<'_>>,
    symbol_names: &[Option<String>],
    scratch_scalars: &mut Vec<ScalarValue>,
    completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<()> {
    let candidate = || {
        candidate_input.ok_or_else(|| {
            datafusion_common::internal_datafusion_err!(
                "MATCH_RECOGNIZE retained candidate projection has no input binding"
            )
        })
    };
    let mut work = CoarseWorkBatch::new(completed);
    let result = (|| {
        for (index, cell) in state_cells.iter().enumerate() {
            let decoded = (|| {
                let value = cell.read(registers, nav_state, symbol_names)?;
                let scalar = match value {
                    BoundStateRead::Scalar(scalar) => scalar,
                    BoundStateRead::CandidateStart(column) => {
                        candidate()?.scalar(column)?
                    }
                    BoundStateRead::RetainedRow { column, row } => {
                        candidate()?.scalar_at(column, row)?
                    }
                    BoundStateRead::AccumulatorOwned => {
                        return datafusion_common::internal_err!(
                            "MATCH_RECOGNIZE physical scratch hydration requires VM-owned cells"
                        );
                    }
                };
                if scalar.data_type() == *cell.output_type() {
                    Ok(scalar)
                } else {
                    scalar.cast_to(cell.output_type())
                }
            })();
            let accounting = work.complete_one();
            let scalar = decoded?;
            accounting?;
            if index == scratch_scalars.len() {
                scratch_scalars.push(scalar);
            } else {
                scratch_scalars[index] = scalar;
            }
        }
        scratch_scalars.truncate(state_cells.len());

        Ok(())
    })();
    work.finish_result(result)
}

/// The planned and executable forms share one descriptor; only their handles
/// differ. Binding resolves column names and checks register ranges once.
pub(crate) type BoundStateSource =
    StateCellSource<ResolvedInputColumn, RegisterId, BoundNavigation>;
pub(crate) type BoundNavigation = NavigationSource<NavigationLookup>;

impl BoundNavigation {
    #[inline]
    pub(crate) fn lookup(&self) -> NavigationLookup {
        self.location
    }
}

impl BoundStateSource {
    pub(super) fn try_bind(
        source: &AggregateValueSource,
        output_type: &DataType,
        schema: &Schema,
        register_layout: &RegisterLayout,
        aggregate_idx: usize,
    ) -> Result<Self> {
        let register = |slot, width, label| {
            RegisterId::try_bind(slot, width, register_layout.num_slots(), label)
                .map_err(|err| invalid_source(aggregate_idx, err.to_string()))
        };
        let column = |name: &str| {
            let column = resolve_optional_column(schema, name).ok_or_else(|| {
                invalid_source(
                    aggregate_idx,
                    format!("source column {name:?} is missing from the input schema"),
                )
            })?;
            require_exact_output_type(
                source,
                output_type,
                schema.field(column.index()).data_type(),
                aggregate_idx,
            )?;
            Ok::<_, DataFusionError>(column)
        };
        let mut bound = match source {
            AggregateValueSource::CandidateStart { column: name } => {
                Self::CandidateStart {
                    column: column(name)?,
                }
            }
            AggregateValueSource::RetainedRow { slot, column: name } => {
                Self::RetainedRow {
                    slot: register(*slot, 1, "retained-row register source")?,
                    column: column(name)?,
                }
            }
            AggregateValueSource::Register { slot } => Self::Register {
                slot: register(*slot, 1, "register source")?,
            },
            AggregateValueSource::Avg {
                sum_slot,
                count_slot,
            } => Self::Avg {
                sum_slot: register(*sum_slot, 1, "AVG sum register")?,
                count_slot: register(*count_slot, 1, "AVG count register")?,
            },
            AggregateValueSource::AvgDecimal128 {
                sum_slot,
                count_slot,
                scale_factor,
            } => Self::AvgDecimal128 {
                sum_slot: register(*sum_slot, 2, "Decimal128 AVG sum register")?,
                count_slot: register(*count_slot, 1, "Decimal128 AVG count register")?,
                scale_factor: *scale_factor,
            },
            AggregateValueSource::Variance {
                state_slot,
                projection,
            } => Self::Variance {
                state_slot: register(*state_slot, 3, "variance state")?,
                projection: *projection,
            },
            AggregateValueSource::RegisterD128 { slot } => Self::RegisterD128 {
                slot: register(*slot, 2, "Decimal128 register source")?,
            },
            AggregateValueSource::AccumulatorOwned => Self::AccumulatorOwned,
            AggregateValueSource::Navigation(_) => {
                let input = source
                    .navigation_input(register_layout)
                    .map_err(|message| invalid_source(aggregate_idx, message))?
                    .ok_or_else(|| {
                        invalid_source(
                            aggregate_idx,
                            format!("unsupported source {source:?}"),
                        )
                    })?;
                let layout = register_layout
                    .navigation_layout()
                    .expect("resolved navigation input requires a layout");
                match input.domain {
                    NavigationValueDomain::Classifier => require_exact_output_type(
                        source,
                        output_type,
                        &DataType::Utf8,
                        aggregate_idx,
                    )?,
                    _ => {
                        column(input.column_name)?;
                    }
                }
                let slot = |index| {
                    NavigationSlotId::try_bind(
                        index,
                        input.domain.storage_width(),
                        layout.num_nav_slots,
                        "navigation slot",
                    )
                    .map(|slot| slot.index())
                };
                let location = match input.location {
                    NavigationLocation::First(index) => NavigationLookup::First {
                        nav_slot: slot(index)?,
                    },
                    NavigationLocation::Last(index) => NavigationLookup::Last {
                        nav_slot: slot(index)?,
                    },
                    NavigationLocation::Prev(index) => NavigationLookup::Prev {
                        nav_slot: slot(index)?,
                    },
                    NavigationLocation::PrevBuffer { index, depth } => {
                        NavigationLookup::PrevBuffer {
                            buffer_idx: PreviousBufferId::try_bind(
                                index,
                                input.domain.storage_width(),
                                layout.num_prev_buffers,
                                "PREV buffer",
                            )?
                            .index(),
                            // RegisterLayout::validate guarantees depth <= buffer.depth <= MAX_PREV_DEPTH.
                            offset: depth + 1,
                        }
                    }
                };
                Self::Navigation(BoundNavigation {
                    location,
                    domain: input.domain,
                    default_value: input.default_value.cloned(),
                })
            }
        };
        validate_decimal_output_envelope(output_type).map_err(|err| {
            invalid_source(
                aggregate_idx,
                format!("invalid decimal output type {output_type}: {err}"),
            )
        })?;
        bind_navigation_default(&mut bound, source, output_type, aggregate_idx)?;
        Ok(bound)
    }

    #[inline]
    pub(crate) const fn is_register_state_local(&self) -> bool {
        matches!(
            self,
            Self::Register { .. }
                | Self::Avg { .. }
                | Self::AvgDecimal128 { .. }
                | Self::Variance { .. }
                | Self::RegisterD128 { .. }
        )
    }
}

fn bind_navigation_default(
    bound: &mut BoundStateSource,
    source: &AggregateValueSource,
    output_type: &DataType,
    aggregate_idx: usize,
) -> Result<()> {
    let BoundStateSource::Navigation(navigation) = bound else {
        return Ok(());
    };
    let Some(value) = navigation.default_value.take() else {
        return Ok(());
    };
    if matches!(&value, ScalarValue::FixedSizeBinary(width, Some(bytes)) if usize::try_from(*width).ok() != Some(bytes.len()))
    {
        return Err(invalid_source(
            aggregate_idx,
            format!(
                "source {source:?} has a fixed binary default with an invalid byte length"
            ),
        ));
    }
    validate_decimal_scalar_value(&value).map_err(|error| {
        invalid_source(
            aggregate_idx,
            format!("source {source:?} has an invalid decimal default: {error}"),
        )
    })?;
    let bound = if value.is_null() {
        ScalarValue::try_from(output_type).map_err(|error| {
            invalid_source(
                aggregate_idx,
                format!(
                    "source {source:?} default could not be typed as {output_type}: {error}"
                ),
            )
        })?
    } else {
        let source_type = value.data_type();
        value.cast_to(output_type).map_err(|error| {
            invalid_source(
                aggregate_idx,
                format!(
                    "source {source:?} default cannot be cast from {source_type} to {output_type}: {error}"
                ),
            )
        })?
    };
    validate_decimal_scalar_value(&bound).map_err(|error| {
        invalid_source(
            aggregate_idx,
            format!(
                "source {source:?} default is invalid after binding to {output_type}: {error}"
            ),
        )
    })?;
    navigation.default_value = Some(bound);
    Ok(())
}

fn validate_decimal_output_envelope(
    output_type: &DataType,
) -> std::result::Result<(), datafusion::arrow::error::ArrowError> {
    let value = match output_type {
        DataType::Decimal128(precision, scale) => {
            ScalarValue::Decimal128(None, *precision, *scale)
        }
        DataType::Decimal256(precision, scale) => {
            ScalarValue::Decimal256(None, *precision, *scale)
        }
        _ => return Ok(()),
    };
    validate_decimal_scalar_value(&value)
}

fn require_exact_output_type(
    source: &AggregateValueSource,
    output_type: &DataType,
    expected: &DataType,
    aggregate_idx: usize,
) -> Result<()> {
    if output_type != expected {
        return Err(invalid_source(
            aggregate_idx,
            format!(
                "source {source:?} uses {expected} encoding, incompatible with aggregate output type {output_type}"
            ),
        ));
    }
    Ok(())
}

fn invalid_source(aggregate_idx: usize, reason: String) -> DataFusionError {
    DataFusionError::Internal(format!(
        "MATCH_RECOGNIZE VM scratch source binding failed for aggregate {aggregate_idx}: {reason}"
    ))
}

pub(super) fn word_to_scalar(value: u64, dt: &DataType) -> Result<ScalarValue> {
    scalar_from_state_word(value, dt).ok_or_else(|| {
        datafusion_common::internal_datafusion_err!(
            "unsupported VM state scalar data type {dt}"
        )
    })
}

pub(crate) fn scalar_from_state_word(value: u64, dt: &DataType) -> Option<ScalarValue> {
    match dt {
        DataType::Boolean => Some(ScalarValue::Boolean(Some(value != 0))),
        DataType::Int8 => Some(ScalarValue::Int8(Some(value as i8))),
        DataType::Int16 => Some(ScalarValue::Int16(Some(value as i16))),
        DataType::Int32 => Some(ScalarValue::Int32(Some(value as i32))),
        DataType::Int64 => Some(ScalarValue::Int64(Some(value as i64))),
        DataType::UInt8 => Some(ScalarValue::UInt8(Some(value as u8))),
        DataType::UInt16 => Some(ScalarValue::UInt16(Some(value as u16))),
        DataType::UInt32 => Some(ScalarValue::UInt32(Some(value as u32))),
        DataType::UInt64 => Some(ScalarValue::UInt64(Some(value))),
        DataType::Float32 => {
            Some(ScalarValue::Float32(Some(f32::from_bits(value as u32))))
        }
        DataType::Float64 => Some(ScalarValue::Float64(Some(f64::from_bits(value)))),
        _ => temporal_scalar_from_bits(value, dt),
    }
}

fn decimal_scalar(value: Option<i128>, dt: &DataType) -> Result<ScalarValue> {
    match dt {
        DataType::Decimal128(precision, scale) => {
            Ok(ScalarValue::Decimal128(value, *precision, *scale))
        }
        _ => datafusion_common::internal_err!(
            "unsupported VM Decimal128 state data type {dt}"
        ),
    }
}

pub(super) fn navigation_default_scalar(
    default_value: Option<&ScalarValue>,
    dt: &DataType,
) -> Result<ScalarValue> {
    match default_value {
        Some(value) if value.data_type() == *dt => Ok(value.clone()),
        Some(value) => datafusion_common::internal_err!(
            "bound VM navigation default has type {}, expected {dt}",
            value.data_type()
        ),
        None => ScalarValue::try_from(dt),
    }
}

impl BoundNavigation {
    /// Resolve a classifier navigation symbol ID against the automaton's symbol table.
    pub(crate) fn classifier_name(
        symbol_id: u64,
        symbol_names: &[Option<String>],
    ) -> Result<&str> {
        let index = usize::try_from(symbol_id).map_err(|_| {
            datafusion_common::internal_datafusion_err!(
                "MATCH_RECOGNIZE classifier navigation symbol ID {symbol_id} overflows usize"
            )
        })?;
        symbol_names
            .get(index)
            .and_then(Option::as_deref)
            .ok_or_else(|| {
                datafusion_common::internal_datafusion_err!(
                    "MATCH_RECOGNIZE classifier navigation symbol ID {index} is out of bounds"
                )
            })
    }

    /// Decode a present value using the caller’s physical or predicate result type.
    /// Missing history and stored SQL NULL remain separate for default handling.
    fn scalar(
        &self,
        state: NavigationReadView<'_>,
        dt: &DataType,
        symbol_names: &[Option<String>],
    ) -> Result<ScalarValue> {
        fn decode<T>(
            datum: NavigationDatum<T>,
            navigation: &BoundNavigation,
            dt: &DataType,
            value: impl FnOnce(T) -> Result<ScalarValue>,
        ) -> Result<ScalarValue> {
            match datum {
                NavigationDatum::Missing => {
                    navigation_default_scalar(navigation.default_value.as_ref(), dt)
                }
                NavigationDatum::Null => ScalarValue::try_from(dt),
                NavigationDatum::Value(bits) => value(bits),
            }
        }
        match self.domain {
            NavigationValueDomain::Primitive => {
                decode(state.primitive(self.lookup()), self, dt, |word| {
                    word_to_scalar(word, dt)
                })
            }
            NavigationValueDomain::Decimal128 => {
                decode(state.decimal128(self.lookup()), self, dt, |words| {
                    decimal_scalar(Some(i128_from_words(words.0, words.1)), dt)
                })
            }
            NavigationValueDomain::Classifier => {
                decode(state.primitive(self.lookup()), self, dt, |word| {
                    let name = Self::classifier_name(word, symbol_names)?;
                    Ok(ScalarValue::Utf8(Some(name.to_string())))
                })
            }
        }
    }
}

impl BoundStateCell {
    /// Read this aggregate result from the state representation selected while
    /// binding the executable match program.
    pub(crate) fn read(
        &self,
        registers: &[u64],
        nav_state: NavigationReadView<'_>,
        symbol_names: &[Option<String>],
    ) -> Result<BoundStateRead> {
        let dt = &self.output_type;
        let register = |slot: &RegisterId| registers[slot.index()];
        match &self.source {
            BoundStateSource::CandidateStart { column } => {
                return Ok(BoundStateRead::CandidateStart(*column));
            }
            BoundStateSource::AccumulatorOwned => {
                return Ok(BoundStateRead::AccumulatorOwned);
            }
            _ if self.has_no_nonnull_rows(registers) => {
                return Ok(BoundStateRead::Scalar(ScalarValue::try_from(dt)?));
            }
            BoundStateSource::RetainedRow { slot, column } => {
                return Ok(BoundStateRead::RetainedRow {
                    column: *column,
                    row: AbsoluteRow::new(register(slot)),
                });
            }
            BoundStateSource::Register { slot } => word_to_scalar(register(slot), dt),
            BoundStateSource::Navigation(read) => {
                read.scalar(nav_state, dt, symbol_names)
            }
            BoundStateSource::Avg {
                sum_slot,
                count_slot,
            } => Ok(ScalarValue::Float64(register_average(
                register(sum_slot),
                register(count_slot),
            ))),
            BoundStateSource::AvgDecimal128 {
                sum_slot,
                count_slot,
                scale_factor,
            } => {
                let slot = sum_slot.index();
                decimal_scalar(
                    register_decimal_average(
                        i128_from_words(registers[slot], registers[slot + 1]),
                        register(count_slot),
                        *scale_factor,
                    )?,
                    dt,
                )
            }

            BoundStateSource::Variance {
                state_slot,
                projection,
            } => Ok(ScalarValue::Float64(
                VarianceState::from_registers(registers, state_slot.index())
                    .project(*projection),
            )),
            BoundStateSource::RegisterD128 { slot } => {
                let slot = slot.index();
                decimal_scalar(
                    Some(i128_from_words(registers[slot], registers[slot + 1])),
                    dt,
                )
            }
        }
        .map(BoundStateRead::Scalar)
    }
}

#[cfg(test)]
#[path = "vm_scratch_tests.rs"]
mod source_tests;