datafusion-match-recognize 0.55.0

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// 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.

//! Post-sort comparison results shared by residual predicates and Lane membership.

use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
mod navigation;
mod packed;
pub(crate) use navigation::{
    NavigationInput, Neighbor, OffsetColumns, OffsetExpression, StaticAtom,
    StaticFormula, StaticRule, fill_offset_default, is_strict_comparison,
};
pub(crate) use packed::{ColumnPredicate, StaticClassification};
/// Maximum rows per packed classification pass.
pub(crate) const PACKED_CLASSIFY_CHUNK_ROWS: usize = 512;
const PACKED_CLASSIFY_WORK_BUDGET: usize = 2048;
use crate::execution::stream::ordered_input::PhysicalInput;
use crate::nfa::{CompiledAutomaton, MAX_REQUIRED_ANCHORS, RequiredAnchor};
use arrayvec::ArrayVec;
use datafusion::arrow::array::{
    Array, ArrayRef, AsArray, BooleanArray, BooleanBufferBuilder, UInt64Array,
};
use datafusion::arrow::buffer::NullBuffer;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{DataFusionError, Result};
use std::sync::Arc;

#[derive(Debug, Default, Clone, Copy)]
pub(crate) enum PredicateValidity {
    #[default]
    NonNull,
    /// The comparison inherits the raw operand's validity buffer.
    Column(usize),
    /// A compound predicate's NULL result has its own classifier bit.
    NullBit(u64),
}

#[derive(Debug, Default)]
pub(crate) struct ClassifiedPredicate {
    pub(crate) bit: u64,
    pub(crate) passthrough: bool,
    pub(crate) output: usize,
    pub(crate) validity: PredicateValidity,
    pub(crate) symbols: u64,
    pub(crate) and_guards: u64,
}

#[derive(Debug)]
pub(crate) struct DemandedPredicate {
    pub(crate) classifier: Arc<StaticClassification>,
    pub(crate) symbol: crate::core::SymbolId,
    pub(crate) output: usize,
}

#[derive(Debug)]
pub(crate) struct MatchAwareClassification {
    pub(crate) demanded: Vec<DemandedPredicate>,
    pub(crate) offsets_only_demanded: bool,
    pub(crate) classifier: Arc<StaticClassification>,
    pub(crate) predicates: Vec<ClassifiedPredicate>,
    pub(crate) eager: u64,
    pub(crate) lane_column: Option<usize>,
    pub(crate) required: u64,
}

/// Necessary eligibility predicates, expressed in the post-sort Lane word layout.
#[derive(Debug)]
pub(crate) struct PackedAnchors {
    pub(crate) column: usize,
    pub(crate) clauses: ArrayVec<RequiredAnchor, MAX_REQUIRED_ANCHORS>,
    pub(crate) start_mask: u64,
    pub(crate) bounded_jump: bool,
}

impl PackedAnchors {
    pub(crate) fn bind(
        classification: &MatchAwareClassification,
        automaton: &CompiledAutomaton,
    ) -> Option<Self> {
        let column = classification.lane_column?;
        if automaton.min_match_rows() == 0
            || automaton.has_mandatory_start_anchor_prefix()
        {
            return None;
        }
        let guards = classification
            .predicates
            .iter()
            .fold(0, |bits, pred| bits | pred.symbols | pred.and_guards);
        let clauses = Self::translate(automaton.required_anchors(), guards);
        if clauses.is_empty() {
            return None;
        }
        // Stateful starts can remain eager in every word. That is still a
        // useful density estimate; only the selected anchor disproves starts.
        let start_mask = automaton
            .required_anchors()
            .iter()
            .find(|c| c.max_before == Some(0) && c.mask >> 63 == 0)
            .map_or(0, |c| c.mask << 1);
        let bounded_jump = start_mask != 0
            && clauses
                .iter()
                .any(|c| c.max_before.is_some() && c.mask != start_mask);
        Some(Self {
            column,
            clauses,
            start_mask,
            bounded_jump,
        })
    }

    fn translate(
        clauses: &[RequiredAnchor],
        guards: u64,
    ) -> ArrayVec<RequiredAnchor, MAX_REQUIRED_ANCHORS> {
        // NFA symbol 1 occupies bit 0. Lane reserves bit 0, leaving only
        // 63 representable symbols. Every arm of a disjunction must be guarded.
        clauses
            .iter()
            .filter_map(|c| {
                let mask = c.mask << 1;
                (mask >> 1 == c.mask && mask & !guards == 0)
                    .then_some(RequiredAnchor { mask, ..*c })
            })
            .collect()
    }
}

impl MatchAwareClassification {
    pub(crate) fn partition_filter(
        &self,
        anchors: &[RequiredAnchor],
    ) -> Option<Arc<dyn datafusion_hash_grouped_order::PartitionMaskExtractor>> {
        let translated: Vec<_> = anchors
            .iter()
            .filter_map(|anchor| {
                let mut symbols = anchor.mask;
                let mut mask = 0;
                while symbols != 0 {
                    let id = symbols.trailing_zeros() + 1;
                    let bit = 1u64.checked_shl(id)?;
                    // Any necessary precheck suffices for an arm; every arm of the
                    // disjunction must have a guard before the clause can prune.
                    let predicate = self
                        .predicates
                        .iter()
                        .find(|p| (p.symbols | p.and_guards) & bit != 0)?;
                    mask |= predicate.bit;
                    symbols &= symbols - 1;
                }
                Some(RequiredAnchor { mask, ..*anchor })
            })
            .collect();
        self.classifier.partition_filter(self.required, &translated)
    }

    pub(crate) fn cached_demand(
        &self,
        batch: &RecordBatch,
        row: usize,
        symbol: crate::core::SymbolId,
    ) -> Option<bool> {
        let column = self.demanded.iter().find(|p| p.symbol == symbol)?.output;
        let array = batch.column(column).as_boolean();
        array.is_valid(row).then(|| array.value(row))
    }

    pub(crate) fn clean_demanded_symbols(&self, batch: &RecordBatch) -> u64 {
        self.demanded
            .iter()
            .filter(|p| batch.column(p.output).null_count() == 0)
            .fold(0, |mask, p| mask | (1u64 << p.symbol.index()))
    }

    pub(crate) fn needs_neighbors(&self) -> bool {
        self.demanded.iter().any(|p| {
            p.classifier
                .navigation
                .as_ref()
                .is_some_and(|n| n.previous != 0 || n.following != 0)
        }) || self
            .classifier
            .navigation
            .as_ref()
            .is_some_and(|nav| nav.previous != 0 || nav.following != 0)
    }

    /// Prepare private fields at admission for raw comparisons, or after the
    /// complete neighboring window is readable when the classifier needs it.
    pub(crate) async fn prepare(
        &self,
        batch: &RecordBatch,
        input: &mut PhysicalInput,
        admission: &datafusion::execution::memory_pool::MemoryReservation,
        navigation: Option<(usize, NavigationInput<'_>)>,
    ) -> Result<Vec<(usize, ArrayRef)>> {
        let rows = batch.num_rows();
        let mut buffers = self
            .predicates
            .iter()
            .map(|p| {
                (!p.passthrough).then(|| {
                    (
                        BooleanBufferBuilder::new(rows),
                        matches!(p.validity, PredicateValidity::NullBit(_))
                            .then(|| BooleanBufferBuilder::new(rows)),
                    )
                })
            })
            .collect::<Vec<_>>();
        let mut lanes = Vec::<u64>::new();
        if self.lane_column.is_some() {
            lanes
                .try_reserve_exact(rows)
                .map_err(|e| DataFusionError::ResourcesExhausted(e.to_string()))?;
        }
        let mut start = 0;
        let units = self
            .classifier
            .work_per_row
            .max(self.predicates.len())
            .max(1);
        let chunk_rows =
            (PACKED_CLASSIFY_WORK_BUDGET / units).clamp(1, PACKED_CLASSIFY_CHUNK_ROWS);
        let has_lane = self.lane_column.is_some();
        let mut words = [0u64; PACKED_CLASSIFY_CHUNK_ROWS];
        input
            .chunks(|ordered, work| {
                let len = (rows - start).min(chunk_rows);
                let masks = &mut words[..len];
                masks.fill(0);
                self.classifier.classify(batch, start, masks)?;
                if let Some(nav) = &self.classifier.navigation {
                    masks.iter_mut().for_each(|word| *word |= nav.always);
                    if let Some((base, ctx)) =
                        navigation.filter(|_| self.needs_neighbors())
                    {
                        nav.classify(
                            &ordered.history,
                            ctx,
                            (base, batch),
                            start,
                            masks,
                            admission,
                        )?;
                    } else {
                        nav.classify_current(batch, start, masks)?;
                    }
                }
                if has_lane {
                    lanes.resize(start + len, self.eager);
                }
                for (predicate, buffer) in self.predicates.iter().zip(&mut buffers) {
                    if buffer.is_none() && predicate.and_guards == 0 {
                        if has_lane {
                            let bit = predicate.bit;
                            let symbols = predicate.symbols;
                            for (lane, &mask) in
                                lanes[start..start + len].iter_mut().zip(masks.iter())
                            {
                                let hit = ((mask & bit) != 0) as u64;
                                *lane |= symbols & hit.wrapping_neg();
                            }
                        }
                        continue;
                    }
                    for (word_idx, mask_word) in masks.chunks(64).enumerate() {
                        let sub_start = start + word_idx * 64;
                        let sub_len = mask_word.len();
                        let valid = match predicate.validity {
                            PredicateValidity::NonNull => u64::MAX,
                            PredicateValidity::Column(column) => {
                                batch.column(column).nulls().map_or(u64::MAX, |nulls| {
                                    // Each sub-slice is at most one word. Arrow handles its bit offset.
                                    nulls
                                        .buffer()
                                        .bit_chunks(nulls.offset() + sub_start, sub_len)
                                        .iter_padded()
                                        .next()
                                        .unwrap_or_default()
                                })
                            }
                            PredicateValidity::NullBit(bit) => {
                                mask_word.iter().enumerate().fold(0, |word, (i, mask)| {
                                    word | (u64::from(mask & bit == 0) << i)
                                })
                            }
                        };
                        let mut values = 0;
                        for (i, &mask) in mask_word.iter().enumerate() {
                            let matches = mask & predicate.bit != 0;
                            values |= u64::from(matches) << i;
                            if has_lane {
                                let lane = &mut lanes[sub_start + i];
                                if matches {
                                    *lane |= predicate.symbols;
                                } else if valid & (1 << i) != 0 {
                                    // UNKNOWN AND <fallible candidate> still reaches the candidate.
                                    *lane &= !predicate.and_guards;
                                }
                            }
                        }
                        if let Some((bits, validity)) = buffer {
                            bits.append_word(values, sub_len);
                            if let Some(validity) = validity {
                                validity.append_word(valid, sub_len);
                            }
                        }
                    }
                }
                start += len;
                work(len * units)?;
                Ok((start == rows).then_some(()))
            })
            .await?;
        let mut replacements = Vec::new();
        for (predicate, buffer) in self.predicates.iter().zip(buffers) {
            let Some((mut values, validity)) = buffer else {
                continue;
            };
            let nulls = match predicate.validity {
                PredicateValidity::Column(index) => batch.column(index).nulls().cloned(),
                _ => validity
                    .map(|mut valid| NullBuffer::new(valid.finish()))
                    .filter(|n| n.null_count() != 0),
            };
            let array = Arc::new(BooleanArray::new(values.finish(), nulls)) as ArrayRef;
            replacements.push((predicate.output, array));
        }
        for predicate in &self.demanded {
            let mut values = BooleanBufferBuilder::new(rows);
            let mut valid = BooleanBufferBuilder::new(rows);
            let mut at = 0;
            input
                .chunks(|ordered, work| {
                    let len = (rows - at).min(COARSE_WORK_BATCH_SIZE);
                    let mut words = [0; COARSE_WORK_BATCH_SIZE];
                    let masks = &mut words[..len];
                    let result = (|| {
                        predicate.classifier.classify(batch, at, masks)?;
                        if let Some(nav) = &predicate.classifier.navigation {
                            masks.iter_mut().for_each(|m| *m |= nav.always);
                            if let Some((base, context)) = navigation {
                                nav.classify(
                                    &ordered.history,
                                    context,
                                    (base, batch),
                                    at,
                                    masks,
                                    admission,
                                )?;
                            } else {
                                nav.classify_current(batch, at, masks)?;
                            }
                        }
                        Ok::<_, DataFusionError>(())
                    })();
                    // A failed private chunk is unavailable, not FALSE. The original
                    // predicate remains authoritative when a candidate reaches it.
                    let clean = match result {
                        Ok(()) => true,
                        Err(error @ DataFusionError::ResourcesExhausted(_)) => {
                            return Err(error);
                        }
                        Err(_) => false,
                    };
                    for (i, &mask) in masks.iter().enumerate() {
                        let accepted = mask & 1 != 0;
                        values.append(accepted);
                        valid.append(clean);
                        if self.lane_column.is_some() && clean {
                            let bit = 1u64 << predicate.symbol.index();
                            if accepted {
                                lanes[at + i] |= bit;
                            } else {
                                lanes[at + i] &= !bit;
                            }
                        }
                    }
                    at += len;
                    work(len * predicate.classifier.work_per_row.max(1))?;
                    Ok((at == rows).then_some(()))
                })
                .await?;
            replacements.push((
                predicate.output,
                Arc::new(BooleanArray::new(
                    values.finish(),
                    Some(NullBuffer::new(valid.finish())),
                )),
            ));
        }
        if let Some(index) = self.lane_column {
            replacements.push((index, Arc::new(UInt64Array::from(lanes))));
        }
        // Admit the finished arrays before publishing them under the input lease.
        for (_, array) in &replacements {
            admission.try_grow(array.get_array_memory_size())?;
        }
        Ok(replacements)
    }
}

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

    #[test]
    fn packed_anchor_requires_every_disjunct_in_the_lane_word() {
        let clause = |mask| RequiredAnchor {
            mask,
            min_before: 1,
            max_before: Some(4),
        };
        let retained = PackedAnchors::translate(
            &[clause(1), clause(3), clause(5), clause(1 << 63)],
            0b110,
        );
        assert_eq!(retained.as_slice(), &[clause(2), clause(6)]);
    }
    #[test]
    fn partition_anchors_translate_shared_and_reordered_predicate_bits() -> Result<()> {
        use datafusion::arrow::array::Int32Array;
        use datafusion::arrow::datatypes::{DataType, Field, Schema};
        use datafusion::common::ScalarValue;
        use datafusion::logical_expr::Operator;
        let class = MatchAwareClassification {
            demanded: Vec::new(),
            offsets_only_demanded: false,
            classifier: Arc::new(
                StaticClassification::for_predicates(vec![
                    StaticRule::Literal(0, Operator::Eq, ScalarValue::Int32(Some(2))),
                    StaticRule::Constant(false), // A separate NULL bit shifts the next predicate.
                    StaticRule::Literal(0, Operator::Eq, ScalarValue::Int32(Some(1))),
                ])
                .unwrap(),
            ),
            predicates: vec![
                ClassifiedPredicate {
                    bit: 1,
                    symbols: 4,
                    ..Default::default()
                },
                ClassifiedPredicate {
                    bit: 4,
                    symbols: 2,
                    ..Default::default()
                },
            ],
            eager: 0,
            lane_column: None,
            required: 0,
        };
        let anchor = RequiredAnchor {
            mask: 3,
            min_before: 0,
            max_before: Some(0),
        };
        let filter = class.partition_filter(&[anchor]).unwrap();
        let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int32, false)]));
        let batch = RecordBatch::try_new(
            schema,
            vec![Arc::new(Int32Array::from(vec![1, 0, 2]))],
        )?;
        let mut presence = [0; 3];
        filter.accumulate_batch(&batch, &[0, 1, 2], &mut presence)?;
        assert_eq!(filter.required_mask(), 5);
        assert_eq!(presence, [5, 0, 5]);
        assert!(
            class
                .partition_filter(&[RequiredAnchor { mask: 5, ..anchor }])
                .is_none(),
            "an unclassified alternative cannot prove absence"
        );
        Ok(())
    }

    #[tokio::test]
    async fn prepare_packs_multi_word_chunks_across_nulls_and_and_guards() -> Result<()> {
        use crate::execution::common::memory::new_unbounded_state_memory;
        use crate::execution::common::scheduling::SliceControl;
        use crate::execution::storage::buffer::PartitionedBuffer;
        use crate::execution::storage::history_buffer::SharedHistoryBuffer;
        use crate::execution::stream::ordered_input::OrderedInput;
        use datafusion::arrow::array::Int32Array;
        use datafusion::arrow::datatypes::{DataType, Field, Schema};
        use datafusion::common::ScalarValue;
        use datafusion::logical_expr::Operator;
        use std::num::NonZeroUsize;

        // 200 rows > 64 exercises multi-word packing inside a single 512-row chunk,
        // including a non-zero sliced null-buffer offset.
        let raw_values: Vec<Option<i32>> = (0..213)
            .map(|i| match i % 5 {
                0 => None,
                1 => Some(10),
                2 => Some(20),
                3 => Some(30),
                _ => Some(40),
            })
            .collect();
        let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int32, true)]));
        let full = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(Int32Array::from(raw_values)) as ArrayRef],
        )?;
        let batch = full.slice(13, 200);

        let class = MatchAwareClassification {
            demanded: Vec::new(),
            offsets_only_demanded: false,
            classifier: Arc::new(
                StaticClassification::for_predicates(vec![
                    // bit 1: v >= 30 (passthrough lane-only fast path)
                    StaticRule::Literal(0, Operator::GtEq, ScalarValue::Int32(Some(30))),
                    // bit 2: v == 20 (buffered with Column(0) nulls + and_guards)
                    StaticRule::Literal(0, Operator::Eq, ScalarValue::Int32(Some(20))),
                    // bit 4: v == 10 (buffered with NullBit(8))
                    StaticRule::Literal(0, Operator::Eq, ScalarValue::Int32(Some(10))),
                    // bit 8: synthetic NULL bit when v == 40
                    StaticRule::Literal(0, Operator::Eq, ScalarValue::Int32(Some(40))),
                ])
                .unwrap(),
            ),
            predicates: vec![
                ClassifiedPredicate {
                    bit: 1,
                    passthrough: true,
                    output: 1,
                    validity: PredicateValidity::NonNull,
                    symbols: 0b0010,
                    and_guards: 0,
                },
                ClassifiedPredicate {
                    bit: 2,
                    passthrough: false,
                    output: 2,
                    validity: PredicateValidity::Column(0),
                    symbols: 0b0100,
                    and_guards: 0b1000,
                },
                ClassifiedPredicate {
                    bit: 4,
                    passthrough: false,
                    output: 3,
                    validity: PredicateValidity::NullBit(8),
                    symbols: 0b1_0000,
                    and_guards: 0,
                },
            ],
            eager: 0b1000,
            lane_column: Some(4),
            required: 0,
        };

        let state = new_unbounded_state_memory();
        let history = SharedHistoryBuffer::new(Arc::clone(&schema), state.new_empty());
        let mut input = PhysicalInput::new(
            OrderedInput {
                buffer: PartitionedBuffer::new(Arc::clone(&schema), vec![], 1),
                history,
            },
            Default::default(),
            SliceControl::for_test_budget(NonZeroUsize::MAX),
            state.new_empty(),
            None,
        );
        let admission = state.new_empty();
        let replacements = class.prepare(&batch, &mut input, &admission, None).await?;
        let col2 = replacements
            .iter()
            .find(|(idx, _)| *idx == 2)
            .unwrap()
            .1
            .as_boolean();
        let col3 = replacements
            .iter()
            .find(|(idx, _)| *idx == 3)
            .unwrap()
            .1
            .as_boolean();
        let lanes = replacements
            .iter()
            .find(|(idx, _)| *idx == 4)
            .unwrap()
            .1
            .as_primitive::<datafusion::arrow::datatypes::UInt64Type>();

        let vals = batch
            .column(0)
            .as_primitive::<datafusion::arrow::datatypes::Int32Type>();
        for row in 0..200 {
            let v = vals.is_valid(row).then(|| vals.value(row));
            assert_eq!(
                col2.is_valid(row).then(|| col2.value(row)),
                v.map(|x| x == 20),
                "col2 row {row}"
            );
            assert_eq!(
                col3.is_valid(row).then(|| col3.value(row)),
                if v == Some(40) {
                    None
                } else {
                    Some(v == Some(10))
                },
                "col3 row {row}"
            );
            let mut expected_lane = 0b1000u64;
            if v.is_some_and(|x| x >= 30) {
                expected_lane |= 0b0010;
            }
            if v == Some(20) {
                expected_lane |= 0b0100;
            } else if v.is_some() {
                // Non-NULL FALSE clears the AND guard; NULL preserves it.
                expected_lane &= !0b1000;
            }
            if v == Some(10) {
                expected_lane |= 0b1_0000;
            }
            assert_eq!(lanes.value(row), expected_lane, "lane row {row} (v={v:?})");
        }
        Ok(())
    }
}