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

//! Pool-accounted candidate banks, DEFINE values, and compressed lane histories.

use super::LaneState;
use super::ir::LaneScanProgram;
use super::path::LanePathCursor;
use super::path::LanePathRun;
use crate::core::AbsoluteRow;
use crate::core::PhysicalRowCount;
use crate::execution::matching::graph::fallible_vec::filled;
use crate::execution::matching::path::compact_path_node;
use crate::execution::matching::row_loop::compiled_program::ExecutablePatternVariant;
use crate::execution::matching::selection::AcceptingCandidate;
use crate::execution::matching::selection::BestMatch;
use crate::nfa::AutomatonStateId;
use datafusion::common::DataFusionError;
use datafusion::common::Result;
use datafusion::execution::memory_pool::MemoryReservation;
use std::sync::Arc;

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum DirectScan {
    Ready,
    Running,
    Disabled,
}

#[cfg(test)]
mod tests;

/// A recoverable storage limit, distinct from allocation and query errors.
#[derive(Debug)]
pub(crate) struct LaneCapacityMiss {
    detail: &'static str,
}

impl std::fmt::Display for LaneCapacityMiss {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "MATCH_RECOGNIZE {}", self.detail)
    }
}

impl std::error::Error for LaneCapacityMiss {}

pub(crate) fn is_lane_capacity_miss(error: &DataFusionError) -> bool {
    matches!(error, DataFusionError::External(error) if error.is::<LaneCapacityMiss>())
}

fn capacity_error(detail: &'static str) -> DataFusionError {
    DataFusionError::External(Box::new(LaneCapacityMiss { detail }))
}

/// Pool-accounted state for one candidate scan.
///
/// Successors are staged in the inactive bank and cannot become active until
/// `finish_row`.
pub(crate) struct LaneScanState {
    pub(crate) program: Arc<LaneScanProgram>,
    pub(super) direct: DirectScan,
    registers: Box<[u64]>,
    navigation: Box<[u64]>,
    register_words: usize,
    navigation_words: usize,
    pub(crate) lanes: Box<[LaneState]>,
    pub(crate) histories: Box<[LanePathRun]>,
    _memory: MemoryReservation,
    // An idle lane still owns encoded tables after active_variant/cache eviction.
    runtime_memory: Option<Arc<MemoryReservation>>,
    pub(crate) candidate_start: Option<AbsoluteRow>,
    active_bank: usize,
    staging_slot: usize,
    incumbent_slot: usize,
    pub(crate) active_len: usize,
    pub(crate) next_len: usize,
    pub(crate) incumbent: Option<AcceptingCandidate>,
}

#[derive(Clone, Copy)]
pub(crate) struct LaneView<'a> {
    pub(crate) state: LaneState,
    pub(crate) registers: &'a [u64],
    pub(crate) navigation: &'a [u64],
    pub(crate) history: &'a [LanePathRun],
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LaneSuccessorAction {
    Discard,
    Append,
}

#[derive(Clone, Copy)]
pub(crate) struct LanePublication {
    action: LaneSuccessorAction,
    incumbent: Option<AcceptingCandidate>,
    pub(crate) row_complete: bool,
    pub(crate) work: usize,
}

fn invalid() -> DataFusionError {
    DataFusionError::Internal("MATCH_RECOGNIZE invalid lane continuation".into())
}

fn exhausted(message: &'static str) -> DataFusionError {
    DataFusionError::ResourcesExhausted(format!("MATCH_RECOGNIZE {message}"))
}

impl LaneScanState {
    pub(crate) fn is_for(&self, program: &Arc<LaneScanProgram>) -> bool {
        Arc::ptr_eq(&self.program, program)
    }
    /// Runtime-pruned programs must retain their shared lease for the entire
    /// lane lifetime. Plan-owned base programs have no runtime reservation.
    pub(crate) fn retain_variant_memory(&mut self, variant: &ExecutablePatternVariant) {
        debug_assert!(
            variant
                .lane_scan_program()
                .is_some_and(|program| self.is_for(program))
        );
        if self.runtime_memory.is_none() {
            self.runtime_memory = variant.runtime_memory();
        }
    }
    pub(crate) fn discard_candidate(&mut self) {
        self.candidate_start = None;
        self.active_len = 0;
        self.next_len = 0;
        self.incumbent = None;
    }
    pub(crate) const fn candidate_is_live(&self) -> bool {
        self.candidate_start.is_some()
    }
    pub(crate) const fn is_at_row_boundary(&self) -> bool {
        self.next_len == 0
    }
    pub(crate) const fn selection_is_open(&self) -> bool {
        self.active_len != 0 || self.next_len != 0
    }
    pub(crate) fn scratch_registers_mut(&mut self) -> &mut [u64] {
        let slot = self.scratch_slot();
        let words = self.register_words;
        &mut self.registers[slot * words..(slot + 1) * words]
    }
    pub(crate) fn scratch_navigation_mut(&mut self) -> &mut [u64] {
        let slot = self.scratch_slot();
        let words = self.navigation_words;
        &mut self.navigation[slot * words..(slot + 1) * words]
    }
    pub(crate) fn scratch_payload_mut(&mut self) -> (&mut [u64], &mut [u64]) {
        let slot = self.scratch_slot();
        let reg_words = self.register_words;
        let nav_words = self.navigation_words;
        (
            &mut self.registers[slot * reg_words..(slot + 1) * reg_words],
            &mut self.navigation[slot * nav_words..(slot + 1) * nav_words],
        )
    }
    /// Continue a direct prefix at its fork row without replaying earlier rows.
    pub(crate) fn seed_from_direct(
        &mut self,
        match_start: AbsoluteRow,
        state_id: AutomatonStateId,
        runs: &[LanePathRun],
        registers: &[u64],
        navigation: &[u64],
    ) -> Option<usize> {
        if runs.len() > self.program.capacity.path_runs_per_lane {
            return None;
        }
        let history_runs = u32::try_from(runs.len()).ok()?;
        self.reset_candidate(match_start);
        self.lanes[0] = LaneState {
            state_id,
            history_runs,
        };
        if !runs.is_empty() {
            let dst = self.history_range(0).start;
            self.histories[dst..dst + runs.len()].copy_from_slice(runs);
        }
        self.direct = DirectScan::Disabled;
        let reg_words = self.register_words;
        if reg_words != 0 {
            self.registers[..reg_words].copy_from_slice(&registers[..reg_words]);
        }
        let nav_words = self.navigation_words;
        if nav_words != 0 {
            self.navigation[..nav_words].copy_from_slice(&navigation[..nav_words]);
        }
        Some(runs.len() + reg_words + nav_words)
    }

    fn copy_payload(&mut self, source: usize, destination: usize) {
        if self.register_words != 0 {
            self.registers.copy_within(
                source * self.register_words..(source + 1) * self.register_words,
                destination * self.register_words,
            );
        }
        if self.navigation_words != 0 {
            self.navigation.copy_within(
                source * self.navigation_words..(source + 1) * self.navigation_words,
                destination * self.navigation_words,
            );
        }
    }
    fn payload_copy_work(&self) -> usize {
        self.register_words + self.navigation_words
    }

    pub(crate) fn try_new(
        program: Arc<LaneScanProgram>,
        state_memory: &MemoryReservation,
    ) -> Result<Self> {
        let capacity = program.capacity;
        let (
            lane_slots,
            register_slots,
            navigation_slots,
            history_slots,
            scan_resource_bytes,
        ) = super::compiler::resource_layout_with_navigation(
            capacity.live_lanes,
            capacity.path_runs_per_lane,
            program.register_words,
            program.navigation_words,
        )
        .ok_or_else(|| exhausted("lane storage layout exceeds capacity"))?;
        debug_assert_eq!(scan_resource_bytes, capacity.scan_resource_bytes);
        let memory = state_memory.new_empty();
        memory
            .try_resize(scan_resource_bytes)
            .map_err(|error| {
                DataFusionError::ResourcesExhausted(format!(
                    "MATCH_RECOGNIZE lane scan could not reserve {scan_resource_bytes} bytes: {error}"
                ))
            })?;
        let lanes = filled(
            lane_slots,
            LaneState {
                state_id: program.transitions.start_state(),
                history_runs: 0,
            },
            "lane slots",
        )?
        .into_boxed_slice();
        let registers = filled(register_slots, 0, "lane registers")?.into_boxed_slice();
        let navigation =
            filled(navigation_slots, 0, "lane navigation")?.into_boxed_slice();
        let histories = filled(history_slots, LanePathRun::EMPTY, "lane history slots")?
            .into_boxed_slice();
        Ok(Self {
            register_words: program.register_words,
            navigation_words: program.navigation_words,
            program,
            lanes,
            direct: DirectScan::Disabled,
            registers,
            navigation,
            histories,
            _memory: memory,
            runtime_memory: None,
            candidate_start: None,
            active_bank: 0,
            staging_slot: lane_slots - 2,
            incumbent_slot: lane_slots - 1,
            active_len: 0,
            next_len: 0,
            incumbent: None,
        })
    }

    fn reset_candidate(&mut self, match_start: AbsoluteRow) {
        self.candidate_start = Some(match_start);
        self.active_bank = 0;
        self.active_len = 1;
        self.next_len = 0;
        self.incumbent = None;
        self.incumbent_slot = self.lanes.len() - 1;
    }

    pub(crate) fn start_candidate(&mut self, match_start: AbsoluteRow) -> usize {
        self.reset_candidate(match_start);
        self.lanes[0] = LaneState {
            state_id: self.program.transitions.start_state(),
            history_runs: 0,
        };
        self.direct = if self.program.direct_linear {
            DirectScan::Ready
        } else {
            DirectScan::Disabled
        };
        self.registers[..self.register_words]
            .copy_from_slice(&self.program.initial_registers[..self.register_words]);
        self.navigation[..self.navigation_words].fill(0);
        self.payload_copy_work()
    }

    pub(crate) const fn candidate_start(&self) -> Option<AbsoluteRow> {
        self.candidate_start
    }

    pub(crate) const fn incumbent(&self) -> Option<AcceptingCandidate> {
        self.incumbent
    }

    /// Freeze the same winning history for either driver's output. Their
    /// acceptance boundary may differ from the final consumed input row.
    pub(crate) fn selected_runs(&self) -> Result<super::CompactSelection<'_>> {
        let winner = self.incumbent.ok_or_else(|| {
            datafusion::common::internal_datafusion_err!(
                "selected Lane lost its incumbent"
            )
        })?;
        super::CompactSelection::try_new(
            &self.program,
            self.view(self.incumbent_slot).history,
            winner.best_match.match_start_row,
            winner.end_row,
            winner.best_match.row,
        )
    }

    pub(crate) fn incumbent_path(
        &self,
    ) -> Option<(LanePathCursor<'_>, PhysicalRowCount)> {
        let incumbent = self.incumbent?;
        let lane = self.incumbent_view()?;
        let steps = incumbent
            .end_row
            .checked_offset_from(incumbent.best_match.match_start_row)?
            .checked_add(PhysicalRowCount::new(1))?;
        Some((LanePathCursor::new(&self.program, lane.history), steps))
    }

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

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

    fn view(&self, slot: usize) -> LaneView<'_> {
        let state = self.lanes[slot];
        LaneView {
            state,
            registers: &self.registers
                [slot * self.register_words..(slot + 1) * self.register_words],
            navigation: &self.navigation
                [slot * self.navigation_words..(slot + 1) * self.navigation_words],
            history: self.history(slot, state),
        }
    }

    #[cfg(test)]
    pub(crate) fn active(&self, index: usize) -> Option<LaneView<'_>> {
        (index < self.active_len).then(|| self.view(self.active_slot(index)))
    }

    pub(crate) fn active_state(&self, index: usize) -> Option<LaneState> {
        (index < self.active_len).then(|| self.lanes[self.active_slot(index)])
    }

    pub(crate) fn scratch(&self) -> LaneView<'_> {
        self.view(self.scratch_slot())
    }

    pub(crate) fn successor(&self, index: usize) -> Option<LaneView<'_>> {
        (index < self.next_len).then(|| self.view(self.successor_slot(index)))
    }

    pub(crate) fn successor_state(&self, index: usize) -> Option<LaneState> {
        (index < self.next_len).then(|| self.lanes[self.successor_slot(index)])
    }

    pub(crate) fn incumbent_view(&self) -> Option<LaneView<'_>> {
        self.incumbent.map(|_| self.view(self.incumbent_slot))
    }

    /// Stage successors sequentially from the front of the inactive bank in
    /// exact SQL:2016 emission order. A free tail slot holds a provisional
    /// successor until publication without disturbing already-staged lanes.
    pub(crate) fn prepare_transition(
        &mut self,
        source_index: usize,
        stage_in_next: bool,
    ) -> Result<usize> {
        self.staging_slot =
            if stage_in_next && self.next_len < self.program.capacity.live_lanes {
                self.successor_base() + self.next_len
            } else {
                self.lanes.len() - 2
            };
        let source = self.active_slot(source_index);
        let work = self.slot_copy_work(source)?;
        self.copy_slot(source, self.scratch_slot());
        Ok(work)
    }

    /// The only feasible edge owns the last reader of the active payload. The
    /// previous bank becomes an empty successor bank with this slot reserved
    /// as unpublished scratch. Rejection drops it at the row boundary. The
    /// incumbent always has its own slot, including when a predicate fails.
    pub(crate) fn take_single_active(&mut self) {
        debug_assert_eq!((self.active_len, self.next_len), (1, 0));
        self.staging_slot = self.active_slot(0);
        self.active_bank ^= 1;
        self.active_len = 0;
        debug_assert_eq!(self.staging_slot, self.successor_base());
    }

    /// Bind the sole active registers and navigation directly. An ordered
    /// sibling can reject after updating them, so it gets a private payload.
    pub(crate) fn bind_direct_payload(&mut self, speculative: bool) -> usize {
        debug_assert_eq!((self.active_len, self.next_len), (1, 0));
        let active = self.active_slot(0);
        if speculative {
            self.staging_slot = self.lanes.len() - 2;
            self.copy_payload(active, self.staging_slot);
            self.payload_copy_work()
        } else {
            self.staging_slot = active;
            0
        }
    }

    /// Every accepted prefix belongs to the same ordered path. A new winner
    /// can extend the previous winner's last run and append fresh runs. The
    /// resolved earlier runs already occupy the incumbent's slab.
    pub(crate) fn advance_direct_edge(
        &mut self,
        edge_id: usize,
        row: AbsoluteRow,
        governor: &mut crate::execution::common::work::WorkGovernor,
        is_aborted: impl FnOnce() -> bool,
    ) -> Result<()> {
        let active = self.active_slot(0);
        let edge = self.program.transitions.sealed_edge(edge_id);
        let winner = self.program.closure_accepting[edge.next_state_id.index()];
        let next_range = self.program.transitions.sealed_range(edge.next_state_id);
        // A reluctant self-acceptance outranks every remaining continuation.
        let terminal = next_range.is_empty()
            || (winner.is_some()
                && self
                    .program
                    .transitions
                    .sealed_edge(next_range.start)
                    .after_accept);
        let reserve = self.incumbent_slot;
        let copy_winner = winner.is_some() && !terminal;
        let first = if copy_winner && self.incumbent.is_some() {
            (self.lanes[reserve].history_runs as usize).saturating_sub(1)
        } else {
            0
        };
        let mut work = 1;
        if self.staging_slot != active {
            work += self.payload_copy_work();
        }
        if copy_winner {
            // The next edge extends the last run or starts exactly one new run.
            work += self.lanes[active].history_runs as usize + 1 - first
                + self.payload_copy_work();
        }
        governor.record_completed(work, is_aborted)?;
        self.advance_slot(active, edge.source_state_id, edge_id, row)?;
        if self.staging_slot != active {
            self.copy_payload(self.staging_slot, active);
        }
        if let Some(state) = winner {
            let lane = self.lanes[active];
            let receipt = self.acceptance_receipt(
                lane,
                state,
                row.checked_add(PhysicalRowCount::new(1))
                    .ok_or_else(invalid)?,
                row,
            )?;
            if terminal {
                // No successors can reuse this bank. Publication borrows the
                // elected slot until start_candidate initializes the next scan.
                debug_assert_eq!(self.next_len, 0);
                self.incumbent_slot = active;
            } else {
                let end = lane.history_runs as usize;
                let from = self.history_range(active).start;
                let to = self.history_range(reserve).start;
                self.histories
                    .copy_within(from + first..from + end, to + first);
                self.copy_payload(active, reserve);
                self.lanes[reserve] = lane;
            }
            self.incumbent = Some(receipt);
        }
        if terminal {
            self.finish_row();
        }
        Ok(())
    }

    pub(crate) fn apply_scratch_transition(
        &mut self,
        source_state_id: AutomatonStateId,
        edge_id: usize,
        row: AbsoluteRow,
    ) -> Result<()> {
        self.advance_slot(self.scratch_slot(), source_state_id, edge_id, row)
    }

    /// A proved sole continuation keeps its active payload and primary slot.
    pub(crate) fn advance_single_active(
        &mut self,
        source: AutomatonStateId,
        edge_id: usize,
        row: AbsoluteRow,
    ) -> Result<()> {
        debug_assert_eq!((self.active_len, self.next_len), (1, 0));
        self.advance_slot(self.active_slot(0), source, edge_id, row)
    }

    fn advance_slot(
        &mut self,
        slot: usize,
        source_state_id: AutomatonStateId,
        edge_id: usize,
        row: AbsoluteRow,
    ) -> Result<()> {
        row.checked_offset_from(self.candidate_start.ok_or_else(invalid)?)
            .and_then(|steps| steps.as_u64().checked_add(1))
            .ok_or_else(|| exhausted("lane history exceeds u64"))?;
        let mut lane = self.lanes[slot];
        let runs = lane.history_runs as usize;
        let range = self.history_range(slot);
        let edge = self.program.transitions.sealed_edge(edge_id);
        let cycle = self
            .program
            .cycle_position(source_state_id)
            .filter(|(id, phase)| {
                let len = self.program.cycles[*id as usize].len() as u32;
                // Compiler-owned cycles are nonempty and phase is below len.
                let next_phase = if *phase == len - 1 { 0 } else { *phase + 1 };
                self.program.cycle_position(edge.next_state_id) == Some((*id, next_phase))
            });
        let append = if let Some((cycle_id, phase)) = cycle {
            if runs != 0
                && self.histories[range.start + runs - 1].try_extend_cycle(
                    &self.program,
                    edge_id,
                    row,
                    PhysicalRowCount::new(1),
                )?
            {
                None
            } else {
                Some(LanePathRun::cycle(cycle_id, phase, row))
            }
        } else if self.program.optimistic_history {
            let step = PhysicalRowCount::new(1);
            if runs > 0
                && self.histories[range.start + runs - 1]
                    .extend_repeated_edge(edge_id, row, step)?
            {
                None
            } else {
                Some(LanePathRun::repeated_edge(edge_id, row, step))
            }
        } else {
            Some(LanePathRun::edge(edge_id, row))
        };
        if let Some(run) = append {
            if runs >= self.program.capacity.path_runs_per_lane {
                return Err(capacity_error("lane history exceeds its storage capacity"));
            }
            // Extension checks continuity within a cycle; a new run must
            // join the preceding run or begin at the candidate's origin.
            let expected = if runs == 0 {
                self.candidate_start.ok_or_else(invalid)?
            } else {
                let last = self.histories[range.start + runs - 1];
                last.first_row()
                    .checked_add(last.steps())
                    .ok_or_else(|| exhausted("lane history row exceeds u64"))?
            };
            if row != expected {
                return Err(invalid());
            }
            self.histories[range.start + runs] = run;
            lane.history_runs += 1;
        }
        lane.state_id = edge.next_state_id;
        self.lanes[slot] = lane;
        Ok(())
    }

    pub(crate) fn plan_publication(
        &self,
        action: LaneSuccessorAction,
        acceptance: Option<(AutomatonStateId, AbsoluteRow)>,
        end_row: AbsoluteRow,
    ) -> Result<LanePublication> {
        if action == LaneSuccessorAction::Append
            && self.next_len >= self.program.capacity.live_lanes
        {
            return Err(capacity_error(
                "lane successor exceeds its storage capacity",
            ));
        }
        let scratch = self.lanes[self.scratch_slot()];
        let incumbent = acceptance
            .map(|(state_id, row)| {
                self.acceptance_receipt(scratch, state_id, row, end_row)
            })
            .transpose()?;
        let successor_copy = match action {
            LaneSuccessorAction::Discard => false,
            LaneSuccessorAction::Append => {
                self.scratch_slot() != self.successor_base() + self.next_len
            }
        };
        let copies = usize::from(successor_copy) + usize::from(incumbent.is_some());
        let copy_width = self.slot_copy_work(self.scratch_slot())?;
        let work = copies
            .checked_mul(copy_width)
            .and_then(|work| work.checked_add(1))
            .ok_or_else(|| exhausted("lane publication work exceeds usize"))?;
        Ok(LanePublication {
            action,
            incumbent,
            row_complete: acceptance.is_some(),
            work,
        })
    }

    pub(crate) fn publish_scratch(&mut self, publication: LanePublication) {
        if publication.action == LaneSuccessorAction::Append {
            let destination = self.successor_slot(self.next_len);
            self.next_len += 1;
            if destination != self.scratch_slot() {
                self.copy_slot(self.scratch_slot(), destination);
            }
        }
        if let Some(incumbent) = publication.incumbent {
            self.copy_slot(self.scratch_slot(), self.incumbent_slot);
            self.incumbent = Some(incumbent);
        }
    }

    pub(crate) fn finish_row(&mut self) {
        self.active_bank ^= 1;
        self.active_len = self.next_len;
        self.next_len = 0;
    }

    fn acceptance_receipt(
        &self,
        lane: LaneState,
        state_id: AutomatonStateId,
        position: AbsoluteRow,
        end_row: AbsoluteRow,
    ) -> Result<AcceptingCandidate> {
        let match_start = self.candidate_start.ok_or_else(invalid)?;
        end_row
            .checked_offset_from(match_start)
            .ok_or_else(|| exhausted("lane path end precedes its start"))?;
        let closure = self.program.closure_accepting[lane.state_id.index()];
        if closure != Some(state_id)
            || end_row.checked_add(PhysicalRowCount::new(1)) != Some(position)
        {
            return Err(invalid());
        }
        Ok(AcceptingCandidate {
            best_match: BestMatch {
                path_end: compact_path_node(),
                state_id,
                row: position,
                match_start_row: match_start,
            },
            end_row,
        })
    }

    fn active_slot(&self, index: usize) -> usize {
        self.active_bank * self.program.capacity.live_lanes + index
    }

    fn successor_slot(&self, index: usize) -> usize {
        self.successor_base() + index
    }

    fn successor_base(&self) -> usize {
        (self.active_bank ^ 1) * self.program.capacity.live_lanes
    }

    pub(crate) fn scratch_slot(&self) -> usize {
        self.staging_slot
    }

    pub(crate) fn history_range(&self, slot: usize) -> std::ops::Range<usize> {
        let start = slot * self.program.capacity.path_runs_per_lane;
        start..start + self.program.capacity.path_runs_per_lane
    }

    fn slot_copy_work(&self, slot: usize) -> Result<usize> {
        (self.lanes[slot].history_runs as usize)
            .checked_add(self.payload_copy_work())
            .and_then(|width| width.checked_add(1))
            .ok_or_else(|| exhausted("lane slot copy work exceeds usize"))
    }

    fn history(&self, slot: usize, lane: LaneState) -> &[LanePathRun] {
        let range = self.history_range(slot);
        &self.histories[range.start..range.start + lane.history_runs as usize]
    }

    fn copy_slot(&mut self, source: usize, destination: usize) {
        let lane = self.lanes[source];
        let history = self.history_range(source);
        let runs = lane.history_runs as usize;
        self.copy_payload(source, destination);
        if runs != 0 {
            self.histories.copy_within(
                history.start..history.start + runs,
                self.history_range(destination).start,
            );
        }
        self.lanes[destination] = lane;
    }
}