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

//! Register allocation metadata for compiled VM plans.
//!
//! Layout objects map aggregates and extracted inputs to register slots and
//! navigation structures consumed by runtime execution.

use crate::core::MatchMetadataColumn;
use crate::core::vm::NavigationSource;
use datafusion_common::ScalarValue;

use super::{
    AggregateKind, AggregateValueSource, MAX_FIRST_OFFSET, MAX_NAV_SLOTS,
    MAX_PREV_BUFFERS, MAX_PREV_DEPTH, MAX_REGISTERS, MAX_VM_NAV_D128_VALUES,
    MAX_VM_NAV_VALUES, MAX_VM_ROW_VALUES, NavSlotInfo, NavigationInput, NavigationLayout,
    NavigationLocation, NavigationValueDomain, SlotInfo, SlotValueType, VmTier,
};

// Extremes under `f64::total_cmp`, including every NaN payload.
const F64_TOTAL_ORDER_MAX_BITS: u64 = 0x7fff_ffff_ffff_ffff;
const F64_TOTAL_ORDER_MIN_BITS: u64 = 0xffff_ffff_ffff_ffff;
// Extremes under `f32::total_cmp`, stored in the low register word.
const F32_TOTAL_ORDER_MAX_BITS: u64 = 0x7fff_ffff;
const F32_TOTAL_ORDER_MIN_BITS: u64 = 0xffff_ffff;

/// Storage and result projection for one managed aggregate.
///
/// Navigation sources have no register allocation. The default record has no
/// VM-owned state or source and leaves the aggregate to its accumulator.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AggregateLayout {
    /// Allocated register state, absent for navigation and accumulator sources.
    pub slot: Option<SlotInfo>,
    /// Projection read by the bound aggregate value loader.
    pub value_source: AggregateValueSource,
    /// Optional count of non-null inputs for null-on-empty state.
    pub nonnull_count_slot: Option<usize>,
}

impl Default for AggregateLayout {
    fn default() -> Self {
        Self {
            slot: None,
            value_source: AggregateValueSource::AccumulatorOwned,
            nonnull_count_slot: None,
        }
    }
}

/// Immutable register allocation metadata shared by VM planning and execution.
///
/// Use [`RegisterLayout::builder`] for non-empty layouts and validate the
/// complete value with [`RegisterLayoutBuilder::try_build`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct RegisterLayout {
    pub(super) num_slots: usize,
    pub(super) aggregates: Vec<AggregateLayout>,
    pub(super) row_input_names: Vec<String>,
    pub(super) nav_column_names: Vec<String>,
    pub(super) nav_d128_column_names: Vec<String>,
    pub(super) navigation_layout: Option<NavigationLayout>,
    pub(super) row_input_as_float: Vec<bool>,
    pub(super) vm_tier: VmTier,
}

/// Collects a complete [`RegisterLayout`] before structural validation.
#[derive(Debug, Clone, Default)]
pub struct RegisterLayoutBuilder {
    layout: RegisterLayout,
    explicit_vm_tier: Option<VmTier>,
}

impl RegisterLayout {
    /// Starts a builder with complete storage and projection records in aggregate order.
    pub fn builder(
        num_slots: usize,
        aggregates: Vec<AggregateLayout>,
    ) -> RegisterLayoutBuilder {
        RegisterLayoutBuilder {
            layout: Self {
                num_slots,
                aggregates,
                ..Self::default()
            },
            explicit_vm_tier: None,
        }
    }

    /// Check storage capacities and indices once, before any runtime indexing.
    /// Aggregate recipes own the correspondence between updates and projections.
    fn validate(&self) -> Result<(), String> {
        let range = |label: &str, start: usize, width: usize, limit: usize| {
            if width > 0 && start.checked_add(width).is_some_and(|end| end <= limit) {
                Ok(())
            } else {
                Err(format!(
                    "{label} out of bounds (index={start}, width={width}, capacity={limit})"
                ))
            }
        };
        for (label, len, capacity) in [
            ("register slots", self.num_slots, MAX_REGISTERS),
            ("row inputs", self.row_input_names.len(), MAX_VM_ROW_VALUES),
            (
                "navigation inputs",
                self.nav_column_names.len(),
                MAX_VM_NAV_VALUES,
            ),
            (
                "Decimal128 navigation inputs",
                self.nav_d128_column_names.len(),
                MAX_VM_NAV_D128_VALUES,
            ),
            (
                "row input coercions",
                self.row_input_as_float.len(),
                self.row_input_names.len(),
            ),
        ] {
            if len > capacity {
                return Err(format!("{label} capacity exceeded ({len} > {capacity})"));
            }
        }
        for aggregate in &self.aggregates {
            if let Some(slot) = aggregate.slot {
                let width = slot.agg_kind.state_width(slot.value_type);
                if slot.slot_count != width {
                    return Err(
                        "aggregate state width does not match its allocation".into()
                    );
                }
                range("aggregate state", slot.start_slot, width, self.num_slots)?;
            }
            if let Some(slot) = aggregate.nonnull_count_slot {
                range("non-null count", slot, 1, self.num_slots)?;
            }
        }
        if let Some(nav) = &self.navigation_layout {
            if nav.num_nav_slots > MAX_NAV_SLOTS
                || nav.num_prev_buffers > MAX_PREV_BUFFERS
                || (self.vm_tier == VmTier::Compact && nav.has_navigation())
            {
                return Err("navigation capacity exceeded for VM tier".into());
            }
            if nav.first_offsets.len() > nav.first_slots.len()
                || nav
                    .first_offsets
                    .iter()
                    .any(|&offset| offset > MAX_FIRST_OFFSET)
            {
                return Err("FIRST offset out of bounds".into());
            }
            let input = |domain, index| {
                let len = match domain {
                    NavigationValueDomain::Primitive => self.nav_column_names.len(),
                    NavigationValueDomain::Decimal128 => self.nav_d128_column_names.len(),
                    NavigationValueDomain::Classifier => 1,
                };
                range("navigation input", index, 1, len)
            };
            for slot in nav
                .first_slots
                .iter()
                .chain(&nav.last_slots)
                .chain(&nav.prev_slots)
            {
                range(
                    "navigation slot",
                    slot.nav_slot,
                    slot.domain.storage_width(),
                    nav.num_nav_slots,
                )?;
                input(slot.domain, slot.value_idx)?;
            }
            for buffer in &nav.prev_buffer_slots {
                range(
                    "PREV buffer",
                    buffer.buffer_idx,
                    buffer.domain.storage_width(),
                    nav.num_prev_buffers,
                )?;
                input(buffer.domain, buffer.value_idx)?;
                if !(2..=MAX_PREV_DEPTH).contains(&buffer.depth) {
                    return Err("PREV depth out of bounds".into());
                }
            }
        }
        Ok(())
    }

    /// Returns a validated Compact layout for accumulator-only aggregates, with
    /// no VM-owned state, row inputs, or navigation inputs.
    /// [`Default`] has no aggregates and uses the conservative Standard tier.
    pub fn empty_compact(aggregate_count: usize) -> Self {
        Self {
            aggregates: vec![AggregateLayout::default(); aggregate_count],
            vm_tier: VmTier::Compact,
            ..Self::default()
        }
    }

    /// Returns the total number of register words.
    pub fn num_slots(&self) -> usize {
        self.num_slots
    }

    /// Returns storage and projection records in aggregate order.
    pub fn aggregates(&self) -> &[AggregateLayout] {
        &self.aggregates
    }

    /// Returns row-value input column names.
    pub fn row_input_names(&self) -> &[String] {
        &self.row_input_names
    }

    /// Returns one-word navigation input column names.
    pub fn nav_column_names(&self) -> &[String] {
        &self.nav_column_names
    }

    /// Returns the Decimal128 navigation input table.
    pub fn nav_d128_column_names(&self) -> &[String] {
        &self.nav_d128_column_names
    }

    /// Returns navigation slot and buffer metadata, when present.
    pub fn navigation_layout(&self) -> Option<&NavigationLayout> {
        self.navigation_layout.as_ref()
    }

    /// Returns whether any navigation slot or buffer tracks `CLASSIFIER()`.
    pub fn has_classifier_navigation(&self) -> bool {
        self.navigation_layout
            .as_ref()
            .is_some_and(NavigationLayout::has_classifier_navigation)
    }

    /// Returns per-row-input Float64 coercion requirements.
    pub fn row_input_as_float(&self) -> &[bool] {
        &self.row_input_as_float
    }

    /// Returns the selected VM execution tier.
    pub fn vm_tier(&self) -> VmTier {
        self.vm_tier
    }

    /// Returns the number of aggregate row inputs needed.
    pub fn num_row_inputs(&self) -> usize {
        self.row_input_names.len()
    }

    /// Computes initial register values based on aggregate kinds.
    ///
    /// - COUNT, SUM, AVG, and statistical running values start at zero.
    /// - MIN starts at the largest value of its type under its comparison order.
    /// - MAX starts at the smallest value of its type under its comparison order.
    ///
    /// Decimal128 values use two slots containing the corresponding extreme.
    pub fn initial_registers(&self) -> [u64; MAX_REGISTERS] {
        let mut registers = [0u64; MAX_REGISTERS];

        for slot_info in self
            .aggregates
            .iter()
            .filter_map(|aggregate| aggregate.slot.as_ref())
        {
            let start = slot_info.start_slot;

            match slot_info.agg_kind {
                AggregateKind::Min => {
                    // Initialize to maximum value so any real value is smaller
                    match slot_info.value_type {
                        SlotValueType::Int64 => {
                            registers[start] = i64::MAX as u64;
                        }
                        SlotValueType::UInt64 => {
                            registers[start] = u64::MAX;
                        }

                        SlotValueType::Float32 => {
                            registers[start] = F32_TOTAL_ORDER_MAX_BITS;
                        }
                        SlotValueType::Float64 => {
                            registers[start] = F64_TOTAL_ORDER_MAX_BITS;
                        }
                        SlotValueType::Decimal128 => {
                            // i128::MAX split into two u64s (little-endian)
                            registers[start] = u64::MAX; // low bits
                            registers[start + 1] = i64::MAX as u64; // high bits (positive sign)
                        }
                        SlotValueType::RetainedRow => {
                            // Row reference is only valid once its non-null count is non-zero.
                        }
                    }
                }
                AggregateKind::Max => {
                    // Initialize to minimum value so any real value is larger
                    match slot_info.value_type {
                        SlotValueType::Int64 => {
                            registers[start] = i64::MIN as u64;
                        }
                        SlotValueType::UInt64 => {
                            registers[start] = u64::MIN;
                        }

                        SlotValueType::Float32 => {
                            registers[start] = F32_TOTAL_ORDER_MIN_BITS;
                        }
                        SlotValueType::Float64 => {
                            registers[start] = F64_TOTAL_ORDER_MIN_BITS;
                        }
                        SlotValueType::Decimal128 => {
                            // i128::MIN split into two u64s (little-endian)
                            registers[start] = 0; // low bits
                            registers[start + 1] = i64::MIN as u64; // high bits (negative sign)
                        }
                        SlotValueType::RetainedRow => {
                            // Row reference is only valid once its non-null count is non-zero.
                        }
                    }
                }
                AggregateKind::Additive
                | AggregateKind::Avg
                | AggregateKind::Variance
                | AggregateKind::BoolOr => {
                    // Additive, statistical, and Boolean OR state start at 0.
                }
                AggregateKind::BoolAnd => {
                    // Initialize to true identity (1)
                    registers[start] = 1;
                }
            }
        }

        registers
    }
}

impl RegisterLayoutBuilder {
    /// Sets named aggregate row inputs and their Float64 coercion requirements.
    pub fn row_inputs(
        mut self,
        row_input_names: Vec<String>,
        row_input_as_float: Vec<bool>,
    ) -> Self {
        self.layout.row_input_names = row_input_names;
        self.layout.row_input_as_float = row_input_as_float;
        self
    }

    /// Sets navigation input columns and derives their execution tier.
    pub fn navigation_inputs(
        mut self,
        nav_column_names: Vec<String>,
        nav_d128_column_names: Vec<String>,
        navigation_layout: Option<NavigationLayout>,
    ) -> Self {
        self.layout.nav_column_names = nav_column_names;
        self.layout.nav_d128_column_names = nav_d128_column_names;
        self.layout.vm_tier = navigation_layout
            .as_ref()
            .map_or(VmTier::Compact, NavigationLayout::vm_tier);
        self.layout.navigation_layout = navigation_layout;
        self
    }

    /// Overrides the derived tier for a checked over-provisioned layout.
    ///
    /// [`Self::try_build`] rejects a tier whose capacity is too small for the
    /// navigation layout. The override is independent of builder call order.
    #[cfg(test)]
    pub fn vm_tier(mut self, vm_tier: VmTier) -> Self {
        self.explicit_vm_tier = Some(vm_tier);
        self
    }

    /// Builds and validates the structural register layout.
    ///
    /// Physical binding derives each writer’s destination from its managed owner.
    pub fn try_build(mut self) -> Result<RegisterLayout, String> {
        if let Some(vm_tier) = self.explicit_vm_tier {
            self.layout.vm_tier = vm_tier;
        }
        self.layout.validate()?;
        Ok(self.layout)
    }
}

impl AggregateValueSource {
    /// Resolve a managed navigation source against its slot and extraction tables.
    /// Non-navigation projections return `None`. Physical schema binding uses
    /// this lookup, including PREV buffer depth.
    pub fn navigation_input<'a>(
        &'a self,
        registers: &'a RegisterLayout,
    ) -> Result<Option<NavigationInput<'a>>, String> {
        let Self::Navigation(NavigationSource {
            location,
            domain,
            default_value,
        }) = self
        else {
            return Ok(None);
        };
        resolve_navigation_input(*location, *domain, default_value.as_ref(), registers)
            .map(Some)
    }
}

fn resolve_navigation_input<'a>(
    location: NavigationLocation,
    domain: NavigationValueDomain,
    default_value: Option<&'a ScalarValue>,
    registers: &'a RegisterLayout,
) -> Result<NavigationInput<'a>, String> {
    use NavigationLocation as L;
    let label = match location {
        L::First(_) => "FIRST",
        L::Last(_) => "LAST",
        L::Prev(_) => "PREV",
        L::PrevBuffer { .. } => "PREV buffer",
    };
    let layout = registers.navigation_layout.as_ref().ok_or_else(|| {
        format!("aggregate {label} source has no navigation layout metadata")
    })?;
    let slot_input = |slots: &[NavSlotInfo], index| {
        let info = matching_navigation_entry(
            slots.iter().filter(|s| s.nav_slot == index),
            domain,
            |s| s.domain,
            label,
            index,
        )?;
        Ok::<_, String>(info.value_idx)
    };
    let value = match location {
        L::First(index) => slot_input(&layout.first_slots, index)?,
        L::Last(index) => slot_input(&layout.last_slots, index)?,
        L::Prev(index) => slot_input(&layout.prev_slots, index)?,
        L::PrevBuffer { index, depth } => {
            let info = matching_navigation_entry(
                layout
                    .prev_buffer_slots
                    .iter()
                    .filter(|b| b.buffer_idx == index),
                domain,
                |b| b.domain,
                label,
                index,
            )?;
            if depth > info.depth {
                return Err(format!(
                    "aggregate PREV buffer source depth exceeds navigation layout (source={depth}, metadata={})",
                    info.depth
                ));
            }
            info.value_idx
        }
    };
    let column_name: &str = match domain {
        NavigationValueDomain::Primitive => registers
            .nav_column_names
            .get(value)
            .map(String::as_str)
            .ok_or_else(|| {
                format!(
                    "aggregate {label} navigation value index {value} is outside its extraction table"
                )
            })?,
        NavigationValueDomain::Decimal128 => registers
            .nav_d128_column_names
            .get(value)
            .map(String::as_str)
            .ok_or_else(|| {
                format!(
                    "aggregate {label} navigation value index {value} is outside its extraction table"
                )
            })?,
        NavigationValueDomain::Classifier => {
            if value != 0 {
                return Err(format!(
                    "aggregate {label} classifier navigation value index must be zero (idx={value})"
                ));
            }
            MatchMetadataColumn::Classifier.as_ref()
        }
    };
    Ok(NavigationInput {
        location,
        domain,
        column_name,
        default_value,
    })
}

fn matching_navigation_entry<'a, T>(
    mut candidates: impl Iterator<Item = &'a T>,
    expected: NavigationValueDomain,
    domain: impl Fn(&T) -> NavigationValueDomain,
    label: &str,
    storage: usize,
) -> Result<&'a T, String> {
    let first = candidates.next().ok_or_else(|| format!("aggregate {label} source has no matching navigation layout entry (storage={storage})"))?;
    let mut matches = std::iter::once(first)
        .chain(candidates)
        .filter(|entry| domain(entry) == expected);
    let entry = matches.next().ok_or_else(||format!("aggregate {label} source domain disagrees with navigation layout (storage={storage}, source={expected:?})"))?;
    if matches.next().is_some() {
        return Err(format!(
            "aggregate {label} source has ambiguous navigation layout entries (storage={storage})"
        ));
    }
    Ok(entry)
}

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

    use super::super::{NavigationKind, PrevBufferInfo};
    fn complete_navigation_artifact_layout() -> RegisterLayout {
        let slot = |nav_slot, value_idx, domain| -> NavSlotInfo {
            NavSlotInfo {
                symbol_idx: Some(0),
                nav_slot,
                value_idx,
                domain,
            }
        };
        let buffer = |buffer_idx, value_idx, depth, domain| -> PrevBufferInfo {
            PrevBufferInfo {
                symbol_idx: Some(0),
                depth,
                buffer_idx,
                value_idx,
                domain,
            }
        };

        RegisterLayout {
            nav_column_names: vec![
                "first_p".to_string(),
                "last_p".to_string(),
                "prev_p".to_string(),
                "buffer_p".to_string(),
            ],
            nav_d128_column_names: vec![
                "first_d128".to_string(),
                "last_d128".to_string(),
                "prev_d128".to_string(),
                "buffer_d128".to_string(),
            ],
            vm_tier: VmTier::Standard,
            navigation_layout: Some(NavigationLayout {
                num_nav_slots: 9,
                num_prev_buffers: 3,
                first_slots: vec![
                    slot(0, 0, NavigationValueDomain::Primitive),
                    slot(1, 0, NavigationValueDomain::Decimal128),
                ],
                first_offsets: vec![],
                last_slots: vec![
                    slot(3, 1, NavigationValueDomain::Primitive),
                    slot(4, 1, NavigationValueDomain::Decimal128),
                    slot(6, 2, NavigationValueDomain::Primitive),
                    slot(7, 2, NavigationValueDomain::Decimal128),
                ],
                prev_slots: vec![
                    slot(6, 2, NavigationValueDomain::Primitive),
                    slot(7, 2, NavigationValueDomain::Decimal128),
                ],
                prev_buffer_slots: vec![
                    buffer(0, 3, 2, NavigationValueDomain::Primitive),
                    buffer(1, 3, 3, NavigationValueDomain::Decimal128),
                ],
            }),
            ..RegisterLayout::default()
        }
    }

    #[test]
    fn storage_bounds_cover_wide_registers_and_navigation() {
        for value_type in [SlotValueType::Int64, SlotValueType::Decimal128] {
            let width = value_type.slot_count();
            for start in [MAX_REGISTERS - width, MAX_REGISTERS - width + 1, usize::MAX] {
                let layout = RegisterLayout::builder(
                    MAX_REGISTERS,
                    vec![AggregateLayout {
                        slot: Some(SlotInfo::with_kind(
                            start,
                            value_type,
                            0,
                            AggregateKind::Min,
                        )),
                        ..Default::default()
                    }],
                )
                .try_build();
                assert_eq!(layout.is_ok(), start == MAX_REGISTERS - width);
            }
        }
        let layout = complete_navigation_artifact_layout();
        layout.validate().unwrap();
        let mut boundary = layout.clone();
        let nav = boundary.navigation_layout.as_mut().unwrap();
        nav.first_slots[1].nav_slot = nav.num_nav_slots - 2;
        boundary.validate().unwrap();
        let invalid: &[fn(&mut RegisterLayout)] = &[
            |layout| layout.num_slots = MAX_REGISTERS + 1,
            |layout| {
                layout
                    .row_input_names
                    .resize(MAX_VM_ROW_VALUES + 1, String::new())
            },
            |layout| {
                layout
                    .nav_column_names
                    .resize(MAX_VM_NAV_VALUES + 1, String::new())
            },
            |layout| {
                layout
                    .nav_d128_column_names
                    .resize(MAX_VM_NAV_D128_VALUES + 1, String::new())
            },
            |layout| {
                layout.navigation_layout.as_mut().unwrap().num_nav_slots =
                    MAX_NAV_SLOTS + 1
            },
            |layout| {
                layout.navigation_layout.as_mut().unwrap().num_prev_buffers =
                    MAX_PREV_BUFFERS + 1
            },
            |layout| {
                layout.navigation_layout.as_mut().unwrap().first_offsets =
                    vec![MAX_FIRST_OFFSET + 1]
            },
            |layout| {
                let nav = layout.navigation_layout.as_mut().unwrap();
                nav.first_slots[1].nav_slot = nav.num_nav_slots - 1
            },
            |layout| {
                layout.navigation_layout.as_mut().unwrap().first_slots[0].value_idx =
                    MAX_VM_NAV_VALUES
            },
            |layout| {
                layout.navigation_layout.as_mut().unwrap().prev_buffer_slots[0].depth =
                    MAX_PREV_DEPTH + 1
            },
            |layout| {
                layout.navigation_layout.as_mut().unwrap().prev_buffer_slots[0].depth = 1
            },
        ];
        for mutate in invalid {
            let mut invalid = layout.clone();
            mutate(&mut invalid);
            assert!(invalid.validate().is_err());
        }
    }

    #[test]
    fn navigation_writers_follow_symbol_scope_and_share_prev_last_updates() {
        let mut layout = complete_navigation_artifact_layout();
        // An unqualified FIRST is visible to both symbols. The remaining seven
        // stores belong only to symbol zero, including two shared LAST/PREV slots.
        layout.navigation_layout.as_mut().unwrap().first_slots[0].symbol_idx = None;
        assert!(layout.validate_symbol_count(0).is_err());
        layout.validate_symbol_count(2).unwrap();
        let stores = layout.navigation_writers(0);
        assert_eq!(stores.len(), 8);
        assert_eq!(
            stores
                .iter()
                .filter(|w| w.kind == NavigationKind::Prev)
                .count(),
            2
        );
        let peer = layout.navigation_writers(1);
        assert_eq!(peer.len(), 1);
        assert_eq!(peer[0].kind, NavigationKind::First);
        assert_eq!(peer[0].storage_idx, 0);
        assert_eq!(peer[0].domain, NavigationValueDomain::Primitive);
    }

    #[test]
    fn float_min_max_initializers_cover_the_full_total_order() {
        let layout = RegisterLayout {
            aggregates: [
                SlotInfo::with_kind(0, SlotValueType::Float64, 0, AggregateKind::Min),
                SlotInfo::with_kind(1, SlotValueType::Float64, 0, AggregateKind::Max),
                SlotInfo::with_kind(2, SlotValueType::Float32, 0, AggregateKind::Min),
                SlotInfo::with_kind(3, SlotValueType::Float32, 0, AggregateKind::Max),
            ]
            .into_iter()
            .map(|slot| AggregateLayout {
                slot: Some(slot),
                ..Default::default()
            })
            .collect(),
            ..Default::default()
        };

        // The largest NaN payload at each sign is the endpoint of total order.
        let expected = [
            0x7fff_ffff_ffff_ffff,
            u64::MAX,
            0x7fff_ffff,
            u64::from(u32::MAX),
        ];
        assert_eq!(layout.initial_registers()[..4], expected);
    }

    #[test]
    fn uint64_min_max_initializers_cover_the_full_unsigned_domain() {
        let layout = RegisterLayout {
            aggregates: [
                SlotInfo::with_kind(0, SlotValueType::UInt64, 0, AggregateKind::Min),
                SlotInfo::with_kind(1, SlotValueType::UInt64, 0, AggregateKind::Max),
            ]
            .into_iter()
            .map(|slot| AggregateLayout {
                slot: Some(slot),
                ..Default::default()
            })
            .collect(),
            ..Default::default()
        };

        let registers = layout.initial_registers();
        assert_eq!(registers[0], u64::MAX);
        assert_eq!(registers[1], u64::MIN);
    }
}