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

//! Execution-private match paths.
//!
//! This module owns the compact symbol encoding and path representation used by
//! active candidates, together with path reconstruction, comparison, and work
//! accounting. The compiled NFA supplies immutable transitions; execution owns
//! the mutable history created while following them.

use crate::core::AbsoluteRow;
use crate::core::PhysicalRowCount;
use crate::core::SymbolId;
use crate::execution::common::memory::try_reserve_accounted;
use crate::execution::common::progress::CoarseWorkBatch;
use crate::execution::matching::row_loop::lane_scan::path::LanePathCursor;
use crate::execution::matching::row_loop::lane_scan::path::LanePathPosition;
use crate::nfa::CompactPathShape;
use crate::nfa::CompactPrefixSuffixInfo;
use crate::nfa::CompiledAutomaton;
use datafusion_common::DataFusionError;
use datafusion_common::Result;
use datafusion_common::internal_err;
use datafusion_execution::memory_pool::MemoryReservation;

/// Exact equality of the path facts read by deferred predicates.
///
/// Ordered threads establish priority; this projection verifies history
/// equivalence before a later thread can be discarded after a hash match.
pub(crate) trait PathStepEquivalence {
    fn equivalent_steps(&self, left: &PathStep, right: &PathStep) -> bool;
}

/// Complete path-storage choice for one exact executable pattern variant.
#[derive(Clone, Debug)]
pub(crate) enum PathRepresentation {
    ArenaRequired,
    ArenaForced,
    CompactSingle(SymbolId),
    CompactPrefixSuffix(CompactPrefixSuffixInfo),
}

impl PathRepresentation {
    #[inline]
    pub(crate) const fn uses_compact_paths(&self) -> bool {
        matches!(self, Self::CompactSingle(_) | Self::CompactPrefixSuffix(_))
    }
}

pub(crate) fn compact_path_shape_for_skip<'a>(
    automaton: &'a CompiledAutomaton,
    skip: &super::ResolvedAfterMatchSkip,
    eligible: bool,
) -> Option<&'a CompactPathShape> {
    if eligible
        && matches!(
            skip,
            super::ResolvedAfterMatchSkip::PastLastRow
                | super::ResolvedAfterMatchSkip::ToNextRow
        )
    {
        automaton.compact_path_shape()
    } else {
        None
    }
}

/// Seal the common compact proof for eligible static future behavior.
/// Payload policies decide eligibility; graph shape and skip semantics have one owner.
pub(crate) fn select_path_representation(
    automaton: &CompiledAutomaton,
    skip: &super::ResolvedAfterMatchSkip,
    eligible: bool,
    disabled: bool,
) -> PathRepresentation {
    match compact_path_shape_for_skip(automaton, skip, eligible) {
        Some(_) if disabled => PathRepresentation::ArenaForced,
        Some(CompactPathShape::Single(symbol)) => {
            PathRepresentation::CompactSingle(*symbol)
        }
        Some(CompactPathShape::PrefixSuffix(shape)) => {
            PathRepresentation::CompactPrefixSuffix(shape.clone())
        }
        None => PathRepresentation::ArenaRequired,
    }
}

/// Maximum number of user-defined pattern symbols accepted by the compact
/// runtime path encoding.
///
/// Numeric symbol ID `0` is reserved for [`Sym::Empty`]. User symbols use
/// consecutive IDs in `1..=u16::MAX`.
pub(crate) const MAX_USER_SYMBOLS: usize = u16::MAX as usize;

/// Compact symbol encoding stored in matcher paths.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Sym {
    /// Zero-length placeholder inserted for empty matches.
    Empty,
    /// User-defined pattern symbol (0-based ordinal).
    User(u16),
}

impl Sym {
    /// Convert the enum to its consecutive, zero-based numeric index.
    pub(crate) const fn to_index(self) -> usize {
        match self {
            Self::Empty => 0,
            Self::User(n) => 1 + n as usize,
        }
    }

    pub(crate) const fn from_index(idx: usize) -> Self {
        match idx {
            0 => Self::Empty,
            n if n <= MAX_USER_SYMBOLS => Self::User((n - 1) as u16),
            _ => panic!("symbol index exceeds the supported dense symbol ID range"),
        }
    }
}

// Symbol index map (see `Sym::to_index()`):
//   0=Empty, 1+=user-defined symbols (in declaration order)
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) struct PathStep {
    /// Absolute position associated with this path step.
    pub(crate) row: AbsoluteRow,
    pub(crate) sym: Sym,
    /// Whether this step matches an excluded symbol (`Pattern::Exclude`).
    pub(crate) excluded: bool,
}

/// Index into the [`PathNode`] arena.
pub(crate) type PathNodeIndex = u32;

const COMPACT_PATH_NODE: PathNodeIndex = u32::MAX - 1;

/// Encoded path marker for candidates whose path is reconstructed from rows.
#[inline]
pub(crate) const fn compact_path_node() -> PathNodeIndex {
    COMPACT_PATH_NODE
}

#[inline]
pub(crate) const fn is_compact_path_node(index: PathNodeIndex) -> bool {
    index == COMPACT_PATH_NODE
}

#[inline]
pub(crate) const fn is_reserved_path_node(index: PathNodeIndex) -> bool {
    index >= COMPACT_PATH_NODE
}

/// Linked-list node sharing common prefixes in the matcher-owned path arena.
#[derive(Debug, Clone, Copy)]
pub(crate) struct PathNode {
    pub(crate) step: PathStep,
    pub(crate) prev: Option<PathNodeIndex>,
    /// Depth of the node in the path tree (0-based).
    pub(crate) depth: u32,
}

fn path_symbol(symbol_id: SymbolId) -> Result<Sym> {
    let symbol_id = symbol_id.index();
    if !(1..=MAX_USER_SYMBOLS).contains(&symbol_id) {
        return Err(DataFusionError::Internal(format!(
            "MATCH_RECOGNIZE compact path symbol ID {symbol_id} is outside the valid user-symbol range"
        )));
    }
    Ok(Sym::from_index(symbol_id))
}

fn path_row_count(start_row: AbsoluteRow, end_row: AbsoluteRow) -> Result<usize> {
    let distance = end_row.checked_offset_from(start_row).ok_or_else(|| {
        DataFusionError::Internal(format!(
            "MATCH_RECOGNIZE compact path start {start_row} follows end {end_row}"
        ))
    })?;
    let row_count = distance.as_u64().checked_add(1).ok_or_else(|| {
        DataFusionError::ResourcesExhausted(
            "MATCH_RECOGNIZE compact path row count exceeds u64".to_string(),
        )
    })?;
    usize::try_from(row_count).map_err(|_| {
        DataFusionError::ResourcesExhausted(format!(
            "MATCH_RECOGNIZE compact path row count {row_count} cannot be represented as usize"
        ))
    })
}

pub(crate) fn checked_path_node(
    arena: &[PathNode],
    index: PathNodeIndex,
) -> Result<&PathNode> {
    if is_reserved_path_node(index) {
        return Err(DataFusionError::Internal(format!(
            "MATCH_RECOGNIZE path node index {index} is reserved"
        )));
    }
    let index = usize::try_from(index).map_err(|_| {
        DataFusionError::ResourcesExhausted(format!(
            "MATCH_RECOGNIZE path node index {index} exceeds usize"
        ))
    })?;
    arena.get(index).ok_or_else(|| {
        DataFusionError::Internal(format!(
            "MATCH_RECOGNIZE path node index {index} is outside an arena of length {}",
            arena.len()
        ))
    })
}

/// Resumable reverse walk through a frozen arena chain.
pub(crate) struct ArenaPathCursor {
    current: Option<PathNodeIndex>,
    expected_depth: u32,
    len: usize,
}

impl ArenaPathCursor {
    pub(crate) fn try_new(arena: &[PathNode], current: PathNodeIndex) -> Result<Self> {
        let first_depth = checked_path_node(arena, current)?.depth;
        let chain_len = usize::try_from(first_depth)
            .ok()
            .and_then(|depth| depth.checked_add(1))
            .ok_or_else(|| {
                DataFusionError::ResourcesExhausted(format!(
                    "MATCH_RECOGNIZE path depth {first_depth} exceeds usize"
                ))
            })?;
        if chain_len > arena.len() {
            return Err(DataFusionError::Internal(format!(
                "MATCH_RECOGNIZE path depth {first_depth} cannot fit an arena of length {}",
                arena.len()
            )));
        }

        Ok(Self {
            current: Some(current),
            expected_depth: first_depth,
            len: chain_len,
        })
    }

    pub(crate) const fn len(&self) -> usize {
        self.len
    }

    pub(crate) fn try_next(&mut self, arena: &[PathNode]) -> Result<Option<PathStep>> {
        let Some(current_idx) = self.current else {
            return Ok(None);
        };
        let expected_depth = self.expected_depth;
        let node = checked_path_node(arena, current_idx)?;
        if node.depth != expected_depth {
            return Err(DataFusionError::Internal(format!(
                "MATCH_RECOGNIZE path node {current_idx} has depth {}, expected {expected_depth}; the chain is malformed or cyclic",
                node.depth
            )));
        }
        match node.prev {
            Some(prev) => {
                if prev >= current_idx {
                    return Err(DataFusionError::Internal(format!(
                        "MATCH_RECOGNIZE path node {current_idx} points to non-older predecessor {prev}; the chain is malformed or cyclic"
                    )));
                }
                self.expected_depth = expected_depth.checked_sub(1).ok_or_else(|| {
                    DataFusionError::Internal(format!(
                        "MATCH_RECOGNIZE root path node {current_idx} has a predecessor; the chain is malformed or cyclic"
                    ))
                })?;
                self.current = Some(prev);
            }
            None => {
                if expected_depth != 0 {
                    return Err(DataFusionError::Internal(format!(
                        "MATCH_RECOGNIZE path node {current_idx} terminates at nonzero depth {expected_depth}"
                    )));
                }
                self.current = None;
            }
        }
        Ok(Some(node.step))
    }
}

/// Scalar progress through immutable compact path segments.
pub(crate) struct CompactPathCursor {
    start: AbsoluteRow,
    len: usize,
    offset: usize,
    segment: usize,
    segment_offset: usize,
    middle_rows: usize,
}

impl CompactPathCursor {
    pub(crate) fn try_single(start: AbsoluteRow, end: AbsoluteRow) -> Result<Self> {
        let len = path_row_count(start, end)?;
        Ok(Self {
            start,
            len,
            offset: 0,
            segment: 0,
            segment_offset: 0,
            middle_rows: len,
        })
    }

    pub(crate) fn try_prefix_suffix(
        shape: &CompactPrefixSuffixInfo,
        start_row: AbsoluteRow,
        end_row: AbsoluteRow,
    ) -> Result<Self> {
        let mut cursor = Self::try_single(start_row, end_row)?;
        let fixed_rows = shape
            .prefix_rows()
            .checked_add(shape.suffix_rows())
            .ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE compact prefix/suffix row count overflow"
                        .to_string(),
                )
            })?;
        let middle_rows = cursor.len.checked_sub(fixed_rows).ok_or_else(|| {
            DataFusionError::Internal(format!(
                "MATCH_RECOGNIZE compact prefix/suffix uses {fixed_rows} fixed rows for a {}-row match", cursor.len
            ))
        })?;
        if middle_rows < shape.middle_min_rows() {
            return Err(DataFusionError::Internal(format!(
                "MATCH_RECOGNIZE compact prefix/suffix reconstructed {middle_rows} middle rows below its minimum {}",
                shape.middle_min_rows()
            )));
        }

        cursor.middle_rows = middle_rows;
        Ok(cursor)
    }

    pub(crate) const fn len(&self) -> usize {
        self.len
    }

    pub(crate) fn try_next(
        &mut self,
        prefix: &[(SymbolId, usize)],
        middle: SymbolId,
        suffix: &[(SymbolId, usize)],
    ) -> Result<Option<PathStep>> {
        if self.offset == self.len {
            return Ok(None);
        }
        // Compiled fixed segments are nonempty; only the middle may be skipped.
        loop {
            let (symbol, count) = if self.segment < prefix.len() {
                prefix[self.segment]
            } else if self.segment == prefix.len() {
                (middle, self.middle_rows)
            } else {
                *suffix.get(self.segment - prefix.len() - 1).ok_or_else(|| {
                    DataFusionError::Internal(
                        "MATCH_RECOGNIZE compact path ended before its extent".into(),
                    )
                })?
            };
            if self.segment_offset == count {
                self.segment += 1;
                self.segment_offset = 0;
                continue;
            }
            let row = self
                .start
                .as_u64()
                .checked_add(self.offset as u64)
                .ok_or_else(|| {
                    DataFusionError::ResourcesExhausted(
                        "MATCH_RECOGNIZE compact path row exceeds u64".into(),
                    )
                })?;
            let step = PathStep {
                row: AbsoluteRow::new(row),
                sym: path_symbol(symbol)?,
                excluded: false,
            };
            self.offset += 1;
            self.segment_offset += 1;
            return Ok(Some(step));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{NormalizedPattern, Pattern, RepetitionQuantifier, Symbol};

    fn prefix_suffix_shape(
        prefix_rows: usize,
        middle_min_rows: u32,
        suffix_rows: usize,
    ) -> CompactPrefixSuffixInfo {
        let symbol = |name: &str| Pattern::Symbol(Symbol::Named(name.into()));
        let mut elements = vec![symbol("A"); prefix_rows];
        elements.push(Pattern::Repetition(
            Box::new(symbol("B")),
            RepetitionQuantifier::AtLeast(middle_min_rows),
        ));
        elements.extend(vec![symbol("C"); suffix_rows]);
        let compiled = CompiledAutomaton::compile(
            &NormalizedPattern::Ast(Pattern::Concat(elements)),
            &["A".into(), "B".into(), "C".into()],
        )
        .unwrap();
        let Some(CompactPathShape::PrefixSuffix(shape)) = compiled.compact_path_shape()
        else {
            panic!("expected compiled prefix/suffix metadata");
        };
        shape.clone()
    }

    fn symbol_id(index: usize) -> SymbolId {
        SymbolId::try_new(index, index + 1).expect("test symbols are non-empty")
    }

    fn path_node(row: u64, prev: Option<PathNodeIndex>, depth: u32) -> PathNode {
        PathNode {
            step: PathStep {
                row: AbsoluteRow::new(row),
                sym: Sym::User(0),
                excluded: false,
            },
            prev,
            depth,
        }
    }

    #[test]
    fn arena_cursor_walks_from_tip_to_root_and_stays_exhausted() {
        let arena = [path_node(10, None, 0), path_node(11, Some(0), 1)];
        let mut cursor = ArenaPathCursor::try_new(&arena, 1).unwrap();
        assert_eq!(cursor.len(), 2);
        assert_eq!(cursor.try_next(&arena).unwrap(), Some(arena[1].step));
        assert_eq!(cursor.try_next(&arena).unwrap(), Some(arena[0].step));
        assert_eq!(cursor.try_next(&arena).unwrap(), None);
        assert_eq!(cursor.try_next(&arena).unwrap(), None);
    }

    #[test]
    fn arena_cursor_rejects_invalid_tips_and_malformed_chains() {
        let root = path_node(10, None, 0);
        for (arena, tip, diagnostic) in [
            (vec![root], 1, "outside an arena"),
            (vec![root], compact_path_node(), "reserved"),
            (vec![root], u32::MAX, "reserved"),
            (vec![path_node(10, Some(0), 0)], 0, "non-older predecessor"),
            (
                vec![path_node(10, Some(1), 1), root],
                0,
                "non-older predecessor",
            ),
            (vec![path_node(10, None, 1), root], 0, "nonzero depth"),
            (
                vec![path_node(10, None, 1), path_node(11, Some(0), 1)],
                1,
                "expected 0",
            ),
            (vec![path_node(10, None, 2), root], 0, "cannot fit an arena"),
        ] {
            let result = (|| {
                let mut cursor = ArenaPathCursor::try_new(&arena, tip)?;
                while cursor.try_next(&arena)?.is_some() {}
                Ok::<(), DataFusionError>(())
            })();
            let error = result.expect_err(diagnostic);
            assert!(matches!(error, DataFusionError::Internal(_)), "{error}");
            assert!(error.to_string().contains(diagnostic), "{error}");
        }
    }

    #[test]
    fn compact_cursor_preserves_wide_rows_and_maximum_symbol() {
        let origin = AbsoluteRow::new(u64::from(u32::MAX) + 10_000);
        let mut cursor =
            CompactPathCursor::try_single(origin, AbsoluteRow::new(origin.as_u64() + 2))
                .unwrap();
        assert_eq!(cursor.len(), 3);
        for offset in 0..3 {
            let step = cursor
                .try_next(&[], symbol_id(MAX_USER_SYMBOLS), &[])
                .unwrap()
                .unwrap();
            assert_eq!(step.row, AbsoluteRow::new(origin.as_u64() + offset));
            assert_eq!(step.sym.to_index(), MAX_USER_SYMBOLS);
        }
        assert_eq!(cursor.try_next(&[], symbol_id(1), &[]).unwrap(), None);
    }

    #[test]
    fn compact_cursor_checks_extent_and_symbol_boundaries() {
        let reversed =
            CompactPathCursor::try_single(AbsoluteRow::new(10), AbsoluteRow::new(9))
                .err()
                .expect("reversed extent");
        assert!(matches!(reversed, DataFusionError::Internal(_)));
        let overflowing =
            CompactPathCursor::try_single(AbsoluteRow::ZERO, AbsoluteRow::MAX)
                .err()
                .expect("inclusive row count exceeds u64");
        assert!(matches!(
            overflowing,
            DataFusionError::ResourcesExhausted(_)
        ));

        let mut cursor =
            CompactPathCursor::try_single(AbsoluteRow::MAX, AbsoluteRow::MAX).unwrap();
        assert_eq!(cursor.len(), 1);
        let error = cursor
            .try_next(&[], symbol_id(MAX_USER_SYMBOLS + 1), &[])
            .expect_err("oversized symbols must return an error rather than panic");
        assert!(matches!(error, DataFusionError::Internal(_)));
        assert_eq!(
            cursor
                .try_next(&[], symbol_id(1), &[])
                .unwrap()
                .unwrap()
                .row,
            AbsoluteRow::MAX,
        );
        assert_eq!(cursor.try_next(&[], symbol_id(1), &[]).unwrap(), None);
    }

    #[test]
    fn segmented_cursor_preserves_wide_rows_and_symbol_order() {
        let shape = prefix_suffix_shape(1, 1, 1);
        let origin = AbsoluteRow::new(u64::from(u32::MAX) + 20_000);
        let mut cursor = CompactPathCursor::try_prefix_suffix(
            &shape,
            origin,
            AbsoluteRow::new(origin.as_u64() + 3),
        )
        .unwrap();
        assert_eq!(cursor.len(), 4);
        for (offset, symbol) in [(0, 1), (1, 2), (2, 2), (3, 3)] {
            let step = cursor
                .try_next(shape.prefix(), shape.middle_symbol(), shape.suffix())
                .unwrap()
                .unwrap();
            assert_eq!(step.row, AbsoluteRow::new(origin.as_u64() + offset));
            assert_eq!(step.sym.to_index(), symbol);
        }
        assert_eq!(
            cursor
                .try_next(shape.prefix(), shape.middle_symbol(), shape.suffix())
                .unwrap(),
            None,
        );
    }

    #[test]
    fn segmented_cursor_requires_fixed_rows_and_compiled_middle_minimum() {
        for (prefix, middle_min, suffix, last_row, expected) in [
            (2, 1, 1, 11, None), // Fixed prefix/suffix exceed the two-row extent.
            (1, 2, 1, 12, None), // One middle row cannot satisfy a minimum of two.
            (1, 2, 1, 13, Some(&[1, 2, 2, 3][..])), // Exact compiled minimum.
            (1, 0, 1, 11, Some(&[1, 3][..])), // Empty middle between fixed segments.
        ] {
            let shape = prefix_suffix_shape(prefix, middle_min, suffix);
            let result = CompactPathCursor::try_prefix_suffix(
                &shape,
                AbsoluteRow::new(10),
                AbsoluteRow::new(last_row),
            );
            match result {
                Ok(mut cursor) => {
                    let expected = expected.expect("invalid shape/extent must fail");
                    let mut symbols = Vec::new();
                    while let Some(step) = cursor
                        .try_next(shape.prefix(), shape.middle_symbol(), shape.suffix())
                        .unwrap()
                    {
                        symbols.push(step.sym.to_index());
                    }
                    assert_eq!(symbols, expected);
                }
                Err(error) => {
                    assert!(expected.is_none(), "{error}");
                    assert!(matches!(error, DataFusionError::Internal(_)));
                }
            }
        }
    }
}

enum SelectedStepCursor {
    Empty(PathStep),
    Arena(ArenaPathCursor),
    Compact(CompactPathCursor),
    Lane(LanePathPosition),
}

/// The driver lends its frozen sources afresh for each bounded poll.
#[derive(Default)]
pub(crate) struct SelectedStepSources<'a> {
    pub(crate) arena: &'a [PathNode],
    pub(crate) shape: Option<&'a PathRepresentation>,
    pub(crate) lane: Option<LanePathCursor<'a>>,
}

pub(crate) struct SelectedSteps {
    cursor: SelectedStepCursor,
    steps: Vec<PathStep>,
    len: usize,
    filled: usize,
    complete: bool,
}

impl SelectedSteps {
    fn new(cursor: SelectedStepCursor, len: usize) -> Self {
        Self {
            cursor,
            steps: Vec::new(),
            len,
            filled: 0,
            complete: false,
        }
    }

    pub(crate) fn empty(step: PathStep) -> Self {
        Self::new(SelectedStepCursor::Empty(step), 1)
    }

    pub(crate) fn arena(nodes: &[PathNode], tip: PathNodeIndex) -> Result<Self> {
        let cursor = ArenaPathCursor::try_new(nodes, tip)?;
        let len = cursor.len();
        Ok(Self::new(SelectedStepCursor::Arena(cursor), len))
    }

    pub(crate) fn compact(
        shape: &PathRepresentation,
        start: AbsoluteRow,
        end: AbsoluteRow,
    ) -> Result<Self> {
        let cursor = match shape {
            PathRepresentation::CompactSingle(_) => {
                CompactPathCursor::try_single(start, end)?
            }
            PathRepresentation::CompactPrefixSuffix(shape) => {
                CompactPathCursor::try_prefix_suffix(shape, start, end)?
            }
            _ => {
                return internal_err!(
                    "selected compact path lost its reconstruction shape"
                );
            }
        };
        let len = cursor.len();
        Ok(Self::new(SelectedStepCursor::Compact(cursor), len))
    }

    pub(crate) fn lane(len: PhysicalRowCount) -> Result<Self> {
        let len = usize::try_from(len.as_u64()).map_err(|_| {
            DataFusionError::ResourcesExhausted("selected Lane path exceeds usize".into())
        })?;
        Ok(Self::new(
            SelectedStepCursor::Lane(LanePathPosition::default()),
            len,
        ))
    }

    /// Inspect a sealed zero-width winner without allocating a one-step path.
    pub(crate) fn empty_position(
        &self,
        arena: &[PathNode],
    ) -> Result<Option<AbsoluteRow>> {
        let step = match &self.cursor {
            SelectedStepCursor::Empty(step) => *step,
            SelectedStepCursor::Arena(cursor) if cursor.len == 1 => {
                checked_path_node(arena, cursor.current.expect("unconsumed path"))?.step
            }
            _ => return Ok(None),
        };
        Ok(matches!(step.sym, Sym::Empty).then_some(step.row))
    }

    pub(crate) fn reserve(
        &mut self,
        mut reuse: Vec<PathStep>,
        memory: &mut MemoryReservation,
    ) -> Result<()> {
        if self.filled != 0 {
            return internal_err!("cannot replace a partially initialized selected path");
        }
        reuse.clear();
        try_reserve_accounted(&mut reuse, memory, self.len, "selected output path")?;
        self.steps = reuse;
        Ok(())
    }

    pub(crate) fn in_reverse(&self) -> bool {
        matches!(self.cursor, SelectedStepCursor::Arena(_))
    }
    pub(crate) fn uses_lane(&self) -> bool {
        matches!(self.cursor, SelectedStepCursor::Lane(_))
    }

    #[inline]
    pub(crate) fn advance(
        &mut self,
        mut source: SelectedStepSources<'_>,
        limit: usize,
        observe: &mut impl FnMut(PathStep) -> Result<()>,
        completed: &mut impl FnMut(usize) -> Result<()>,
    ) -> Result<bool> {
        if self.complete {
            return Ok(true);
        }
        if self.steps.capacity() < self.len {
            return internal_err!("selected output path was not reserved");
        }
        if let SelectedStepCursor::Lane(position) = &self.cursor {
            source
                .lane
                .as_mut()
                .ok_or_else(|| {
                    datafusion_common::internal_datafusion_err!(
                        "selected Lane lost its cursor"
                    )
                })?
                .resume_at(*position);
        }
        let end = self.filled.saturating_add(limit).min(self.len);
        let mut work = CoarseWorkBatch::new(completed);
        while self.filled < end {
            let step = match &mut self.cursor {
                SelectedStepCursor::Empty(step) => Some(*step),
                SelectedStepCursor::Arena(cursor) => cursor.try_next(source.arena)?,
                SelectedStepCursor::Compact(cursor) => match source.shape {
                    Some(PathRepresentation::CompactSingle(symbol)) => {
                        cursor.try_next(&[], *symbol, &[])?
                    }
                    Some(PathRepresentation::CompactPrefixSuffix(shape)) => cursor
                        .try_next(
                            shape.prefix(),
                            shape.middle_symbol(),
                            shape.suffix(),
                        )?,
                    _ => {
                        return internal_err!(
                            "selected compact path lost its reconstruction shape"
                        );
                    }
                },
                SelectedStepCursor::Lane(_) => source
                    .lane
                    .as_mut()
                    .expect("cursor bound above")
                    .try_next()?,
            }
            .ok_or_else(|| {
                datafusion_common::internal_datafusion_err!(
                    "selected path ended before its declared length"
                )
            })?;
            observe(step)?;
            if self.in_reverse() {
                self.steps.spare_capacity_mut()[self.len - self.filled - 1].write(step);
            } else {
                self.steps.push(step);
            }
            self.filled += 1;
            work.complete_one()?;
        }
        work.finish()?;
        if let SelectedStepCursor::Lane(position) = &mut self.cursor {
            let cursor = source.lane.as_mut().expect("cursor bound above");
            if self.filled == self.len && cursor.try_next()?.is_some() {
                return internal_err!("selected Lane exceeds its declared path length");
            }
            *position = cursor.position();
        }
        self.complete = self.filled == self.len;
        Ok(self.complete)
    }

    pub(crate) fn finish(mut self) -> Result<Vec<PathStep>> {
        if !self.complete {
            return internal_err!("published incomplete selected path");
        }
        if self.in_reverse() {
            // SAFETY: every slot in the reserved prefix was initialized exactly
            // once by its reverse cursor; no partially filled vector is exposed.
            unsafe {
                self.steps.set_len(self.len);
            }
        }
        Ok(self.steps)
    }
}