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
// 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 register and navigation types and state-update instructions.

use datafusion_common::ScalarValue;
use std::fmt;

mod register_layout;
mod words;

pub use register_layout::{AggregateLayout, RegisterLayout};
pub(crate) use words::i128_from_words;
pub use words::{
    compare_i128, is_temporal_word_type, temporal_scalar_from_bits,
    temporal_scalar_to_bits, wrapping_add_i128_to_registers,
};

/// Number of registers stored inline inside `ActiveNFAState` and
/// stack-allocated direct-linear cursors.
pub const MAX_INLINE_REGISTERS: usize = 16;

/// Maximum number of registers in the VM.
///
/// Layouts using at most [`MAX_INLINE_REGISTERS`] words stay inline inside
/// `ActiveNFAState`; wider layouts spill into an accounted copy-on-write
/// register frame on `ActiveThread`. Individual aggregates may consume multiple
/// registers, so register allocation is driven by slot metadata rather than
/// one-register-per-aggregate assumptions.
pub const MAX_REGISTERS: usize = 64;

/// Maximum number of primitive SUM or extracted row values loaded for one VM step.
pub const MAX_VM_ROW_VALUES: usize = MAX_REGISTERS;

/// Capacity of primitive inputs for navigation slots and PREV buffers together.
pub const MAX_VM_NAV_VALUES: usize = MAX_NAV_SLOTS + MAX_PREV_BUFFERS;

/// Capacity of two-word inputs for navigation slots and PREV buffers together.
pub const MAX_VM_NAV_D128_VALUES: usize = MAX_NAV_SLOTS / 2 + MAX_PREV_BUFFERS / 2;

/// VM execution tier, selected based on navigation requirements.
///
/// Controls navigation capacity and whether a candidate can allocate a frame:
/// - **Compact**: No navigation functions used — candidates keep navigation absent
///   and allocate no frame storage.
/// - **Standard**: Up to 16 navigation slots and 16 PREV buffers in
///   packed navigation frames. PREV-only layouts also use this tier; buffered
///   depths range from 2 through [`MAX_PREV_DEPTH`].
///
/// Layouts exceeding either capacity or the maximum PREV depth use Accumulator state.
///
/// `ActiveNFAState` itself is the same size across tiers because navigation
/// state is owned separately by `ActiveThread` rather than stored inline.
///
/// Tier selection happens during state-update assembly based on `NavigationLayout`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum VmTier {
    /// No navigation — candidates allocate no navigation frame.
    Compact,
    /// Navigation slots or PREV buffers, up to 16 of each.
    #[default]
    Standard,
}

impl fmt::Display for VmTier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            VmTier::Compact => "Compact",
            VmTier::Standard => "Standard",
        })
    }
}

/// The type of value stored in a slot, determining how many u64 registers it uses.
///
/// Different types require different numbers of registers:
/// - Int64/UInt64/Float32/Float64: 1 slot (up to 64 bits)
/// - Decimal128: 2 slots (128 bits)
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum SlotValueType {
    /// Signed integer or temporal coefficient - uses 1 slot.
    #[default]
    Int64,
    /// Unsigned integer - uses 1 slot.
    UInt64,

    /// 32-bit float preserving its raw bit pattern in the low word - uses 1 slot
    Float32,
    /// 64-bit float (SUM(float_col)) - uses 1 slot
    Float64,
    /// 128-bit decimal (SUM(decimal128_col)) - uses 2 slots
    Decimal128,
    /// Retained input row reference (`AbsoluteRow`) for byte-comparable `MIN`/`MAX` - uses 1 slot
    RetainedRow,
}

impl SlotValueType {
    /// Returns the number of u64 registers required for this type.
    #[inline]
    pub fn slot_count(&self) -> usize {
        match self {
            Self::Int64
            | Self::UInt64
            | Self::Float32
            | Self::Float64
            | Self::RetainedRow => 1,
            Self::Decimal128 => 2,
        }
    }
}

/// The kind of aggregate operation for a slot.
///
/// This determines each register's initial value. Counts, sums, averages, and
/// statistical running values start at zero. MIN starts at the largest value of
/// its input type, and MAX starts at the smallest value under the type's total
/// comparison order.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum AggregateKind {
    /// COUNT(*) or SUM(col) - initialize to 0
    #[default]
    Additive,
    /// MIN(col) - initialize to maximum value
    Min,
    /// MAX(col) - initialize to minimum value
    Max,
    /// AVG(col) - SUM + COUNT pair, both initialize to 0.
    ///
    /// For Int64/Float64: 2 slots (sum, count)
    /// For Decimal128: 3 slots (sum_low, sum_high, count)
    Avg,
    /// STDDEV/VAR family - Welford mean, M2, and count initialize to 0.
    ///
    /// Layout: `[mean, m2, count]` (3 slots).
    Variance,
    /// BOOL_AND(col) - initialize to 1 (true identity)
    BoolAnd,
    /// BOOL_OR(col) - initialize to 0 (false identity)
    BoolOr,
}

impl AggregateKind {
    /// Number of registers occupied by the aggregate state for this value type.
    pub(super) fn state_width(self, value_type: SlotValueType) -> usize {
        match self {
            Self::Avg => value_type.slot_count() + 1,
            Self::Variance => 3,
            _ => value_type.slot_count(),
        }
    }
}

/// Metadata about a slot allocation in the register file.
///
/// For multi-register types (Decimal128), `slot_count > 1` and the aggregate
/// spans consecutive registers starting at `start_slot`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct SlotInfo {
    /// Starting register slot index.
    pub start_slot: usize,
    /// Number of consecutive slots, including extra count or running-sum slots.
    pub slot_count: usize,
    /// Value type determining slot width and comparison semantics.
    pub value_type: SlotValueType,
    /// Decimal scale (for Decimal128), 0 for non-decimal values.
    pub scale: i8,
    /// Aggregate kind for initialization behavior.
    pub agg_kind: AggregateKind,
}

impl SlotInfo {
    /// Creates a new slot info with default aggregate kind (Additive).
    #[cfg(test)]
    #[inline]
    pub fn new(start_slot: usize, value_type: SlotValueType, scale: i8) -> Self {
        Self::with_kind(start_slot, value_type, scale, AggregateKind::Additive)
    }

    /// Creates a new slot info with explicit aggregate kind.
    #[inline]
    pub fn with_kind(
        start_slot: usize,
        value_type: SlotValueType,
        scale: i8,
        agg_kind: AggregateKind,
    ) -> Self {
        Self {
            start_slot,
            slot_count: agg_kind.state_width(value_type),
            value_type,
            scale,
            agg_kind,
        }
    }

    /// Returns the count slot for AVG/statistical aggregates, if present.
    ///
    /// For AVG: count slot is at `start_slot + sum_width`.
    /// For statistical aggregates: count slot is always the last slot.
    #[inline]
    pub fn count_slot(&self) -> Option<usize> {
        match self.agg_kind {
            AggregateKind::Avg | AggregateKind::Variance => {
                Some(self.start_slot + (self.agg_kind.state_width(self.value_type) - 1))
            }
            _ => None,
        }
    }

    /// Creates an Int64 slot.
    #[cfg(test)]
    #[inline]
    pub fn int64(start_slot: usize) -> Self {
        Self::new(start_slot, SlotValueType::Int64, 0)
    }

    /// Creates a Decimal128 slot.
    #[cfg(test)]
    #[inline]
    pub fn decimal128(start_slot: usize, scale: i8) -> Self {
        Self::new(start_slot, SlotValueType::Decimal128, scale)
    }
}

/// Maximum depth for PREV circular buffers.
///
/// A depth-31 buffer holds 32 entries (current row plus 31 predecessors), which
/// fills one 64-bit status word at 2 bits per entry.
pub const MAX_PREV_DEPTH: usize = 31;

/// Maximum logical offset supported by VM `FIRST(x, k)` navigation slots.
pub const MAX_FIRST_OFFSET: usize = u8::MAX as usize;

/// Maximum number of navigation slots for the Standard tier.
pub const MAX_NAV_SLOTS: usize = 16;

/// Maximum number of deep PREV buffers for the Standard tier.
pub const MAX_PREV_BUFFERS: usize = 16;

/// Storage and binding domain for one navigation value.
///
/// Primitive values and runtime classifier symbol IDs occupy one navigation
/// word; Decimal128 occupies two. FixedSizeBinary and Decimal256 managed
/// navigation uses Accumulator state instead of introducing a VM navigation
/// domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NavigationValueDomain {
    /// Boolean, numeric, or temporal value stored in one word.
    Primitive,
    /// Decimal128 value stored in two consecutive words.
    Decimal128,
    /// Runtime NFA symbol ID for `CLASSIFIER()` stored in one word.
    Classifier,
}

impl NavigationValueDomain {
    /// Number of consecutive navigation slots or PREV buffers used per value.
    pub const fn storage_width(self) -> usize {
        match self {
            Self::Primitive | Self::Classifier => 1,
            Self::Decimal128 => 2,
        }
    }
}

/// Information about a navigation slot (FIRST/LAST/PREV with depth=1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NavSlotInfo {
    /// Symbol index this slot tracks, or `None` when it tracks every symbol.
    pub symbol_idx: Option<usize>,
    /// Navigation slot index in the logical navigation layout.
    pub nav_slot: usize,
    /// Index into the domain-specific navigation extraction vector.
    pub value_idx: usize,
    /// Extraction-index domain and storage width for this value.
    pub domain: NavigationValueDomain,
}

/// Information about a PREV buffer (depth > 1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PrevBufferInfo {
    /// Symbol index this buffer tracks, or `None` when it tracks every symbol.
    pub symbol_idx: Option<usize>,
    /// PREV depth (e.g., 3 for `PREV(A.col, 3)`).
    pub depth: usize,
    /// Buffer index in the logical PREV-buffer layout.
    pub buffer_idx: usize,
    /// Index into the domain-specific navigation extraction vector.
    pub value_idx: usize,
    /// Extraction-index domain and storage width for this value.
    pub domain: NavigationValueDomain,
}

/// Layout of navigation state for a specific query.
///
/// Tracks which navigation slots and PREV buffers are used and provides
/// metadata for value extraction at execution time.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct NavigationLayout {
    /// Number of FIRST/LAST/PREV(depth=1) slots used.
    pub num_nav_slots: usize,

    /// Number of PREV circular buffers used (depth > 1).
    pub num_prev_buffers: usize,

    /// Mapping info for FIRST slots.
    pub first_slots: Vec<NavSlotInfo>,

    /// Optional logical offsets for `first_slots` (`0` = first row, `k` = `(k + 1)`-th row).
    ///
    /// Indexed in parallel with `first_slots`; omitted trailing entries default to `0`.
    pub first_offsets: Vec<usize>,

    /// Mapping info for LAST slots.
    pub last_slots: Vec<NavSlotInfo>,

    /// Mapping info for PREV(depth=1) slots.
    pub prev_slots: Vec<NavSlotInfo>,

    /// Mapping info for PREV(depth>1) buffers.
    pub prev_buffer_slots: Vec<PrevBufferInfo>,
}

impl NavigationLayout {
    /// Returns the logical offset for `first_slots[index]`, defaulting to `0`.
    #[inline]
    pub fn first_slot_offset(&self, index: usize) -> usize {
        self.first_offsets.get(index).copied().unwrap_or(0)
    }

    /// Returns true if navigation is used in this query.
    pub fn has_navigation(&self) -> bool {
        self.num_nav_slots > 0 || self.num_prev_buffers > 0
    }

    /// Returns true if any navigation slot or buffer tracks `CLASSIFIER()`.
    pub fn has_classifier_navigation(&self) -> bool {
        self.first_slots
            .iter()
            .chain(&self.last_slots)
            .chain(&self.prev_slots)
            .any(|slot| slot.domain == NavigationValueDomain::Classifier)
            || self
                .prev_buffer_slots
                .iter()
                .any(|buffer| buffer.domain == NavigationValueDomain::Classifier)
    }

    /// Returns the VM tier for this navigation layout.
    ///
    /// Compact needs no navigation; every nonempty layout uses Standard.
    /// Assembly rejects layouts exceeding its 16-slot or 16-buffer capacity.
    pub fn vm_tier(&self) -> VmTier {
        if self.has_navigation() {
            VmTier::Standard
        } else {
            VmTier::Compact
        }
    }
}

/// Denominator convention for an exact online statistical state projection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StatisticalPopulation {
    /// Divide by one fewer than the number of non-NULL inputs.
    Sample,
    /// Divide by the number of non-NULL inputs.
    Population,
}

/// Result projected from a shared `(mean, M2, count)` state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VarianceProjection {
    /// Return variance using the selected denominator convention.
    Variance(StatisticalPopulation),
    /// Return the square root of variance using the selected convention.
    Stddev(StatisticalPopulation),
}

/// Managed aggregate projection source used during physical binding.
///
/// Physical construction binds each variant for bound predicate and fallback readers
/// so both use the same current projection. `slot`, `state_slot`, and
/// [`NavigationLocation`] identify the first 64-bit word; Decimal128 values
/// occupy two consecutive words. `default_value` is returned
/// only when the requested navigation position does not exist. A position that
/// exists and contains SQL `NULL` remains null.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StateCellSource<Column, Register, Navigation> {
    /// Plain FIRST proved to read the first physical row of every candidate.
    /// The retained input owns the value; no aggregate state is allocated.
    CandidateStart { column: Column },
    /// Read from VM register file at the given slot.
    Register { slot: Register },
    /// Read from packed navigation at the given location and value domain.
    Navigation(Navigation),
    /// Read non-Decimal128 AVG from a Float64 sum word and count in VM registers.
    ///
    /// At runtime: if count=0 -> NULL, else avg = sum_f64 / count_f64.
    /// The sum word always stores Float64 bits, including for integer inputs.
    Avg {
        sum_slot: Register,
        count_slot: Register,
    },
    /// Read AVG from Decimal128 SUM + COUNT slots in VM register file.
    ///
    /// At runtime: if count=0 -> NULL, else avg_i128 = (sum_i128 * scale_factor) / count.
    AvgDecimal128 {
        sum_slot: Register,
        count_slot: Register,
        scale_factor: u32,
    },
    /// Project VAR or STDDEV from `[mean, M2, count]`.
    Variance {
        state_slot: Register,
        projection: VarianceProjection,
    },
    /// Read Decimal128 value from VM register file (2 consecutive slots).
    RegisterD128 { slot: Register },
    /// Read a byte-comparable `MIN`/`MAX` value from retained input at the
    /// `AbsoluteRow` stored in `slot` (valid only when its non-null tracker is non-zero).
    RetainedRow { slot: Register, column: Column },
    /// Accumulator-owned aggregate with no register or navigation projection.
    AccumulatorOwned,
}

/// Planned aggregate projection; physical binding resolves columns and indices
/// into the same source descriptor used by every runtime reader.
pub type AggregateValueSource =
    StateCellSource<String, usize, NavigationSource<NavigationLocation>>;

/// A navigation location, its packed domain, and its missing-history default.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NavigationSource<Location> {
    /// Resolved once when binding the consumer.
    pub location: Location,
    /// Packed value representation.
    pub domain: NavigationValueDomain,
    /// Used only for missing history, never for a stored SQL NULL.
    pub default_value: Option<ScalarValue>,
}

/// Location of a managed navigation read in the layout's packed history.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NavigationLocation {
    /// First accepted row for the symbol.
    First(usize),
    /// Last accepted row, also used for PREV with offset zero.
    Last(usize),
    /// Previous accepted row in the coupled LAST/PREV slot.
    Prev(usize),
    /// First word of a deep PREV buffer and its SQL offset.
    PrevBuffer { index: usize, depth: usize },
}

/// History location and canonical extraction column for a managed aggregate.
#[derive(Debug, Clone, Copy)]
pub struct NavigationInput<'a> {
    /// Role and physical storage offset.
    pub location: NavigationLocation,
    /// Packed value representation and width.
    pub domain: NavigationValueDomain,
    /// Exact spelling from the domain's extraction table.
    pub column_name: &'a str,
    /// Caller-supplied default for a missing position. Physical binding casts it to the output type.
    pub default_value: Option<&'a ScalarValue>,
}

/// One accepted row's update to an aggregate, in managed aggregate order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RegisterWriter {
    /// COUNT(*), or COUNT(input) when its validity bitmap is required.
    Count {
        aggregate: usize,
        input: Option<usize>,
    },
    /// Apply the owner's typed aggregate update and its paired counter.
    Accumulate {
        aggregate: usize,
        input: usize,
        nullable: bool,
    },
}

impl RegisterWriter {
    /// The managed aggregate whose state this writer updates.
    pub const fn aggregate(&self) -> usize {
        match *self {
            Self::Count { aggregate, .. } | Self::Accumulate { aggregate, .. } => {
                aggregate
            }
        }
    }

    /// The input whose SQL validity governs the whole update.
    pub const fn null_input(&self) -> Option<usize> {
        match *self {
            Self::Count { input, .. } => input,
            Self::Accumulate {
                input,
                nullable: true,
                ..
            } => Some(input),
            Self::Accumulate { .. } => None,
        }
    }
}

/// Navigation history updated by one state instruction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NavigationKind {
    /// Store the first accepted value.
    First,
    /// Store the latest accepted value.
    Last,
    /// Retain the preceding and latest accepted values.
    Prev,
    /// Push into a deeper previous-value history.
    PrevBuffer,
}

impl NavigationKind {
    pub(super) const fn label(self) -> &'static str {
        match self {
            Self::First => "FIRST",
            Self::Last => "LAST",
            Self::Prev => "PREV",
            Self::PrevBuffer => "PREV buffer",
        }
    }
}

/// A navigation store derived from its validated layout ownership.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NavigationUpdate {
    /// Navigation history updated by the instruction.
    pub kind: NavigationKind,
    /// Starting word offset in navigation slots or deep-PREV buffers.
    pub storage_idx: u8,
    /// Input index in the domain-specific navigation extraction table.
    pub value_idx: u8,
    /// Logical value domain, including its physical storage width.
    pub domain: NavigationValueDomain,
    /// Target logical offset for `NavigationKind::First` (`0` for all other kinds).
    pub first_offset: u8,
}

// RegisterLayout checks the full storage and input ranges before producing writers.
const _: () = {
    assert!(MAX_NAV_SLOTS <= 256 && MAX_PREV_BUFFERS <= 256);
    assert!(MAX_VM_NAV_VALUES <= 256 && MAX_VM_NAV_D128_VALUES <= 256);
    assert!(MAX_FIRST_OFFSET <= u8::MAX as usize);
};

impl fmt::Display for NavigationUpdate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let operation = match self.kind {
            NavigationKind::First => "StoreFirst",
            NavigationKind::Last => "StoreLast",
            NavigationKind::Prev => "UpdatePrevLast",
            NavigationKind::PrevBuffer => "PushPrevBuffer",
        };
        let suffix = if self.kind == NavigationKind::First && self.first_offset > 0 {
            format!("(+{})", self.first_offset)
        } else {
            String::new()
        };
        match self.domain {
            NavigationValueDomain::Primitive => {
                write!(
                    f,
                    "{operation}{suffix} {} <- value[{}]",
                    self.storage_idx, self.value_idx
                )
            }
            NavigationValueDomain::Decimal128 => {
                write!(
                    f,
                    "{operation}D128{suffix} {} <- decimal[{}]",
                    self.storage_idx, self.value_idx
                )
            }
            NavigationValueDomain::Classifier => {
                write!(
                    f,
                    "{operation}Classifier{suffix} {} <- symbol",
                    self.storage_idx
                )
            }
        }
    }
}

impl RegisterLayout {
    /// Check that every scoped navigation owner is present in the user-symbol table.
    pub fn validate_symbol_count(&self, symbols_len: usize) -> Result<(), String> {
        let Some(layout) = self.navigation_layout() else {
            return Ok(());
        };
        for (kind, symbol_idx, storage_idx) in
            layout
                .first_slots
                .iter()
                .map(|info| (NavigationKind::First, info.symbol_idx, info.nav_slot))
                .chain(
                    layout.last_slots.iter().map(|info| {
                        (NavigationKind::Last, info.symbol_idx, info.nav_slot)
                    }),
                )
                .chain(
                    layout.prev_slots.iter().map(|info| {
                        (NavigationKind::Prev, info.symbol_idx, info.nav_slot)
                    }),
                )
                .chain(layout.prev_buffer_slots.iter().map(|info| {
                    (NavigationKind::PrevBuffer, info.symbol_idx, info.buffer_idx)
                }))
        {
            if symbol_idx.is_some_and(|idx| idx >= symbols_len) {
                return Err(format!(
                    "navigation {} layout symbol index out of bounds (idx={}, symbols={symbols_len}, storage={storage_idx})",
                    kind.label(),
                    symbol_idx.unwrap_or_default()
                ));
            }
        }
        Ok(())
    }

    /// Return the stores for a logical symbol, including unqualified navigation.
    /// A LAST shared with PREV is written once by the combined PREV store.
    pub fn navigation_writers(&self, symbol_idx: usize) -> Vec<NavigationUpdate> {
        let Some(layout) = self.navigation_layout() else {
            return Vec::new();
        };
        let applies = |scope: Option<usize>| scope.is_none_or(|idx| idx == symbol_idx);
        let slot_artifact =
            |kind, info: &NavSlotInfo, first_offset: u8| NavigationUpdate {
                kind,
                storage_idx: info.nav_slot as u8,
                value_idx: info.value_idx as u8,
                domain: info.domain,
                first_offset,
            };
        let mut expected = layout
            .first_slots
            .iter()
            .enumerate()
            .filter(|(_, info)| applies(info.symbol_idx))
            .map(|(idx, info)| {
                slot_artifact(
                    NavigationKind::First,
                    info,
                    layout.first_slot_offset(idx) as u8,
                )
            })
            .collect::<Vec<_>>();
        expected.extend(
            layout
                .last_slots
                .iter()
                .filter(|info| {
                    applies(info.symbol_idx)
                        && !layout.prev_slots.iter().any(|prev| prev == *info)
                })
                .map(|info| slot_artifact(NavigationKind::Last, info, 0)),
        );
        expected.extend(
            layout
                .prev_slots
                .iter()
                .filter(|info| applies(info.symbol_idx))
                .map(|info| slot_artifact(NavigationKind::Prev, info, 0)),
        );
        expected.extend(
            layout
                .prev_buffer_slots
                .iter()
                .filter(|info| applies(info.symbol_idx))
                .map(|info| NavigationUpdate {
                    kind: NavigationKind::PrevBuffer,
                    storage_idx: info.buffer_idx as u8,
                    value_idx: info.value_idx as u8,
                    domain: info.domain,
                    first_offset: 0,
                }),
        );
        expected
    }
}

/// Returns whether `MIN`/`MAX` on `data_type` is stored as a retained-row
/// reference (`AbsoluteRow`) in a single VM register slot and compared via
/// Arrow's unsigned byte-slice lexicographic order.
pub fn is_retained_row_extrema_type(
    data_type: &datafusion::arrow::datatypes::DataType,
) -> bool {
    use datafusion::arrow::datatypes::DataType;
    matches!(
        data_type,
        DataType::Utf8
            | DataType::LargeUtf8
            | DataType::Utf8View
            | DataType::Binary
            | DataType::LargeBinary
            | DataType::BinaryView
            | DataType::FixedSizeBinary(_)
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn aggregate_state_widths_match_register_layout_contract() {
        for (kind, value_type, expected_width) in [
            (AggregateKind::Additive, SlotValueType::Int64, 1),
            (AggregateKind::Additive, SlotValueType::Decimal128, 2),
            (AggregateKind::Avg, SlotValueType::Int64, 2),
            (AggregateKind::Avg, SlotValueType::Decimal128, 3),
            (AggregateKind::Variance, SlotValueType::Float64, 3),
        ] {
            let info = SlotInfo::with_kind(0, value_type, 0, kind);
            assert_eq!(info.slot_count, expected_width, "{kind:?} {value_type:?}");
        }
    }

    #[test]
    fn navigation_input_capacity_includes_slots_and_prev_buffers() {
        for (domain, width, limit) in [
            (NavigationValueDomain::Primitive, 1, 32),
            (NavigationValueDomain::Decimal128, 2, 16),
        ] {
            let mut navigation = NavigationLayout {
                num_nav_slots: MAX_NAV_SLOTS,
                num_prev_buffers: MAX_PREV_BUFFERS,
                ..Default::default()
            };
            for index in 0..MAX_NAV_SLOTS / width {
                navigation.first_slots.push(NavSlotInfo {
                    symbol_idx: None,
                    nav_slot: index * width,
                    value_idx: index,
                    domain,
                });
            }
            for index in 0..MAX_PREV_BUFFERS / width {
                navigation.prev_buffer_slots.push(PrevBufferInfo {
                    symbol_idx: None,
                    depth: 2,
                    buffer_idx: index * width,
                    value_idx: MAX_NAV_SLOTS / width + index,
                    domain,
                });
            }
            for count in [limit, limit + 1] {
                let names = (0..count).map(|i| format!("c{i}")).collect();
                let (primitive, decimal) = match domain {
                    NavigationValueDomain::Primitive => (names, Vec::new()),
                    NavigationValueDomain::Decimal128 => (Vec::new(), names),
                    NavigationValueDomain::Classifier => unreachable!(),
                };
                // try_build runs the private RegisterLayout::validate check.
                let result = RegisterLayout::builder(0, Vec::new())
                    .navigation_inputs(primitive, decimal, Some(navigation.clone()))
                    .try_build();
                assert_eq!(result.is_ok(), count == limit, "{domain:?}: {count}");
            }
        }
    }
}