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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
// 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.

use std::sync::Arc;

use crate::core::AbsoluteRow;
use datafusion_common::{DataFusionError, Result};

use super::direct_payload::{DirectRouteCounters, DirectRow};
use super::ir::LaneScanProgram;
use super::selection::commit_scratch_transition;
use super::state::{DirectScan, LaneScanState, is_lane_capacity_miss};
use crate::execution::common::coordinates::absolute_row_from_usize;
use crate::execution::common::progress::ComputeStep;
use crate::execution::common::progress::{COARSE_WORK_BATCH_SIZE, CoarseWorkCounter};
use crate::execution::matching::graph::ordered_transitions::OrderedTransitionEdge;
use crate::execution::matching::row_loop::aggregate_engine::{
    AggregateEngine, checked_position_offset,
};
use crate::execution::matching::row_loop::continuation::ScanResources;
use crate::execution::matching::row_loop::predicate_decision::{
    PredicateCacheProbe, TransitionDecision,
};
use crate::execution::matching::row_loop::scan::{RowLoopSession, ScanCoordinates};
use crate::execution::matching::row_loop::state::WorkGovernor;
use crate::execution::matching::row_loop::symbol_evaluator::{LaneRow, LaneRowMasks};
use crate::execution::matching::row_loop::types::{
    NavigationReadView, PackedNavigationFrameView,
};
use crate::execution::matching::row_loop::vm_executor;
use crate::execution::matching::{
    ExecutableIncrementalEvaluator, ExecutableSymbolEvaluator, PatternMatcher,
};
use crate::execution::storage::bound_columns::BoundBatchRow;
use crate::nfa::AutomatonStateId;
#[cfg(test)]
use crate::nfa::CompiledAutomaton;

/// Row masks and route counters belonging to this physical head and executable.
pub(crate) struct LaneCollection {
    pub(crate) row_masks: LaneRowMasks,
    routes: DirectRouteCounters,
}

impl LaneCollection {
    pub(crate) fn new() -> Self {
        Self {
            row_masks: LaneRowMasks::default(),
            routes: DirectRouteCounters::default(),
        }
    }

    pub(crate) fn record_routes(
        &self,
        matcher: &PatternMatcher,
        variant: &super::super::compiled_program::ExecutablePatternVariant,
    ) {
        self.routes.record_routes(matcher, variant);
    }

    #[inline]
    pub(crate) fn merge_direct_routes(&mut self, routes: &DirectRouteCounters) {
        self.routes.merge(routes);
    }

    #[inline]
    pub(crate) fn merge_into(&self, routes: &mut DirectRouteCounters) {
        routes.merge(&self.routes);
    }
}

struct LaneRunner<'m, 'a, 'ctx> {
    matcher: &'m PatternMatcher,
    collection: &'m mut LaneCollection,
    program: &'a LaneScanProgram,
    session: RowLoopSession<'a, 'ctx>,
    coordinates: ScanCoordinates,
}

pub(crate) fn start_local_candidate_scan<'a, 'ctx>(
    matcher: &PatternMatcher,
    program: &'a Arc<LaneScanProgram>,
    session: RowLoopSession<'a, 'ctx>,
    collection: &mut LaneCollection,
) -> Result<ComputeStep> {
    session.ctx.prepare_next_start()?;
    let coordinates = session.coordinates()?;
    let match_start = coordinates.match_start;
    session.ctx.scan_state.reset(session.range.row_idx);
    let candidate_initialization_work = session
        .ctx
        .resources_mut()
        .prepare_lane_scan(program, match_start)?;
    session
        .ctx
        .scan_state
        .governor
        .record_completed(candidate_initialization_work, || matcher.is_aborted())?;
    collection.routes.lane_started += 1;
    if program.requires_partition_start()
        && match_start.as_u64() != session.range.absolute_partition_start as u64
    {
        session
            .ctx
            .resources_mut()
            .lane_scan
            .as_mut()
            .expect("lane state exists")
            .finish_row();
        return Ok(ComputeStep::Complete);
    }
    run_or_restart(matcher, program, session, coordinates, collection)
}

pub(crate) fn resume_candidate_scan<'a, 'ctx>(
    matcher: &PatternMatcher,
    program: &'a Arc<LaneScanProgram>,
    session: RowLoopSession<'a, 'ctx>,
    collection: &mut LaneCollection,
) -> Result<ComputeStep> {
    if session
        .ctx
        .lane_scan_state()
        .is_none_or(|state| !state.is_for(program))
    {
        return datafusion_common::internal_err!(
            "MATCH_RECOGNIZE lane continuation changed executable identity"
        );
    }
    let coordinates = session.coordinates()?;
    run_or_restart(matcher, program, session, coordinates, collection)
}

fn run_or_restart<'a, 'ctx>(
    matcher: &PatternMatcher,
    program: &'a Arc<LaneScanProgram>,
    session: RowLoopSession<'a, 'ctx>,
    coordinates: ScanCoordinates,
    collection: &mut LaneCollection,
) -> Result<ComputeStep> {
    let mut runner = LaneRunner {
        collection,
        matcher,
        program,
        session,
        coordinates,
    };
    let result = runner.run();
    let capacity_miss = matches!(&result, Err(error) if is_lane_capacity_miss(error));
    // Admission proves that every consuming path outranks the root empty
    // acceptance. Let General resolve only the starts with no consuming winner.
    let empty_fallback = matches!(result, Ok(ComputeStep::Complete))
        && runner.session.program.automaton().min_match_rows() == 0
        && runner
            .session
            .ctx
            .lane_scan_state()
            .is_some_and(|lane| lane.incumbent().is_none() && lane.active_len() == 0);
    if !capacity_miss && !empty_fallback {
        return result;
    }

    let mut session = runner.session;
    let restart_row = session
        .ctx
        .lane_scan_state()
        .and_then(LaneScanState::candidate_start)
        .and_then(|start| start.checked_offset_from(coordinates.provider_origin_abs))
        .and_then(|offset| usize::try_from(offset.as_u64()).ok())
        .filter(|&row| row <= coordinates.work_len)
        .ok_or_else(|| invalid("capacity restart escaped retained input"))?;
    // This clears aggregation, traversal, caches and continuation state while
    // preserving completed work and cancellation sampling in WorkGovernor.
    session.ctx.discard_candidate_scan();
    session.ctx.lane_scan = None;
    session.ctx.partition.lane_disabled |= capacity_miss;
    session.range.row_idx = restart_row;
    matcher.start_candidate_scan(session)
}

impl LaneRunner<'_, '_, '_> {
    fn run(&mut self) -> Result<ComputeStep> {
        let input = self.session.source.input_buffer;
        let candidate_bound = self
            .session
            .ctx
            .lane_scan_state()
            .and_then(LaneScanState::candidate_start)
            .and_then(|start| usize::try_from(start.as_u64()).ok())
            .and_then(|start| start.checked_sub(self.session.range.global_row_offset))
            .filter(|&row| row < input.num_rows())
            .and_then(|row| {
                let (batch, local) = input.locate(row);
                input.bound_row(batch, local)
            });
        loop {
            let current_row = self.session.ctx.scan_state.current_row;
            if current_row >= self.coordinates.work_len {
                return Ok(ComputeStep::Complete);
            }
            let active_len = self
                .session
                .ctx
                .lane_scan_state()
                .expect("lane state exists")
                .active_len();
            if active_len == 0 {
                return Ok(ComputeStep::Complete);
            }
            let masks = self.evaluate_symbols()?;
            self.run_row(masks, candidate_bound)?;
            if self
                .session
                .ctx
                .scan_state
                .governor
                .take_yield_if_due_hot(self.session.yield_policy)
            {
                return Ok(ComputeStep::Yield);
            }
        }
    }

    fn evaluate_symbols(&mut self) -> Result<LaneRow> {
        let session = &mut self.session;
        let row = session.ctx.scan_state.current_row;
        let physical_rows = self.coordinates.partition_len;
        if row >= physical_rows {
            return Ok(LaneRow::default());
        }
        let governor = &mut session.ctx.scan_state.governor;
        if let Some(column) = self.matcher.program.packed_lane_column
            && std::ptr::eq(
                session.program,
                self.matcher.program.base_variant().as_ref(),
            )
        {
            use datafusion::arrow::array::AsArray;
            use datafusion::arrow::datatypes::UInt64Type;
            let location = session
                .source
                .provider
                .locate(row)
                .expect("physical Lane row");
            let (batch, local) = self
                .collection
                .row_masks
                .locate_input(session.source.input_buffer, location.local_row)
                .expect("physical Lane input");
            let masks = session
                .source
                .input_buffer
                .batch(batch)
                .column(column)
                .as_primitive::<UInt64Type>();
            governor.record_completed(1, || self.matcher.is_aborted())?;
            return Ok(LaneRow {
                eligible: masks.value(local),
                or_passes: 0,
            });
        }
        self.collection.row_masks.evaluate(
            row,
            session.program.symbol_execution_plan(),
            session.program.symbol_programs(),
            session.source.provider,
            &mut |units| governor.record_completed(units, || self.matcher.is_aborted()),
        )
    }

    fn run_row(
        &mut self,
        masks: LaneRow,
        candidate_bound: Option<BoundBatchRow<'_>>,
    ) -> Result<()> {
        let matcher = self.matcher;
        let program = self.program;
        let session = &mut self.session;
        let current_row = session.ctx.scan_state.current_row;
        let absolute_row = absolute_row_from_usize(
            self.coordinates
                .provider_origin
                .checked_add(current_row)
                .ok_or_else(|| exhausted("transition row"))?,
            "lane transition row",
        )?;
        let can_accept = !program.requires_partition_end()
            || (session.range.has_virtual_row
                && current_row + 1 == self.coordinates.partition_len);
        let partition_start = session.ctx.partition.partition_start_row;
        let next_match_number = session.ctx.partition.next_match_number;
        let executable = session.program;
        let input = session.source.input_buffer;
        let partition_len = self.coordinates.partition_len;
        let global_offset = session.range.global_row_offset;
        let resources = session.ctx.resources_mut();
        let ScanResources {
            aggregation,
            scan_state,
            lane_scan,
            ..
        } = resources;
        let governor = &mut scan_state.governor;
        let lane = lane_scan.as_mut().expect("lane state exists");
        let mut eligible = masks.eligible;
        let mut only_edge = None;
        if lane.active_len() == 1 {
            let source = lane.active_state(0).expect("one active lane").state_id;
            let required = executable
                .automaton()
                .closure_transition_bitmap(program.dispatch_environment(source), source);
            eligible &= required;
            if eligible == 0 {
                governor.record_completed(1, || matcher.is_aborted())?;
                return self.finish_row();
            }
            let range = program.transitions.sealed_range(source);
            // A repeated label can still fork. The shared packed-edge index
            // preserves encounter order. Bound its unindexed fallback search.
            if range.len() == 1 {
                let id = range.start;
                governor.record_completed(1, || matcher.is_aborted())?;
                only_edge = Some((source, id, program.transitions.sealed_edge(id)));
            } else if eligible.is_power_of_two() && range.len() <= COARSE_WORK_BATCH_SIZE
            {
                governor.record_completed(range.len().max(1), || matcher.is_aborted())?;
                if let Some(id) = program.transitions.first_enabled_edge(
                    range,
                    required >> 1,
                    eligible >> 1,
                ) {
                    let edge = program.transitions.sealed_edge(id);
                    if !edge.shares_symbol() {
                        only_edge = Some((source, id, edge));
                    }
                }
            }
        }
        if let Some((_, _, edge)) = only_edge
            && !program.requires_partition_end()
            && edge.after_accept
        {
            governor.record_completed(1, || matcher.is_aborted())?;
            return self.finish_row();
        }
        let candidate_start = lane
            .candidate_start()
            .ok_or_else(|| invalid("missing lane start"))?;
        // The active payload descends from a unique path at every prior row.
        // Only continuations ahead of the prior acceptance remain live.
        let direct = !program.requires_partition_end()
            && !matcher.program.config().compact_paths_disabled
            && lane.direct != DirectScan::Disabled
            && match only_edge {
                Some((_, _, edge)) => !edge.after_accept,
                None if executable.can_retire_ordered_siblings
                    && lane.active_len() == 1 =>
                {
                    let source = lane.active_state(0).expect("one active lane").state_id;
                    let edges = program.transitions.sealed_edges_for_state(source);
                    if edges.len() <= COARSE_WORK_BATCH_SIZE {
                        governor
                            .record_completed(edges.len(), || matcher.is_aborted())?;
                        edges.iter().all(|edge| {
                            eligible & (1 << edge.symbol_id.index()) == 0
                                || (!edge.after_accept
                                    && program.closure_accepting
                                        [edge.next_state_id.index()]
                                    .is_some())
                        })
                    } else {
                        false
                    }
                }
                None => false,
            };
        if !direct {
            lane.direct = DirectScan::Disabled;
        }
        if let Some((source, id, edge)) = only_edge
            && eligible & program.payload_symbols == 0
        {
            let single = lane.incumbent().is_none()
                && program.closure_accepting[edge.next_state_id.index()].is_none()
                && !program
                    .transitions
                    .sealed_range(edge.next_state_id)
                    .is_empty();
            if single || direct {
                match_sequence_number(candidate_start, absolute_row)?;
                if executable.requires_position_offset() {
                    checked_position_offset(candidate_start, absolute_row)?;
                }
                if single {
                    // The same lane owns the ranked history across this row.
                    governor.record_completed(2, || matcher.is_aborted())?;
                    lane.advance_single_active(source, id, absolute_row)?;
                } else {
                    lane.bind_direct_payload(false);
                    lane.advance_direct_edge(id, absolute_row, governor, || {
                        matcher.is_aborted()
                    })?;
                    record_direct_candidate(lane, &mut self.collection.routes.direct);
                }
                scan_state.current_row = current_row + 1;
                #[cfg(test)]
                if let Some(metrics) = &matcher.services.metrics {
                    metrics.accepted_edges.add(1);
                }
                return Ok(());
            }
        }
        let generation = aggregation.define_cache_state.proposed_generation();
        let mut engine = AggregateEngine::new(
            matcher,
            executable,
            input,
            &matcher.program.aggregate_hot_tables().columns,
            aggregation,
            generation,
            partition_start,
            global_offset,
            next_match_number,
        );
        if eligible & program.payload_symbols != 0 {
            let location = partition_start
                .checked_add(current_row)
                .and_then(|row| self.collection.row_masks.locate_input(input, row));
            if let Some((batch, local)) = location
                && let Some(row) = input.bound_row(batch, local)
            {
                engine.current_row = current_row;
                engine.cached_batch_location = location;
                engine.bound_row = Some(row);
                self.collection.routes.used_bound_input = true;
                engine.state.define_cache_state.define_cache_gen = generation;
            } else {
                engine.prepare_or_resume_transition_row(
                    current_row,
                    partition_len,
                    true,
                    &mut |units| {
                        governor.record_completed(units, || matcher.is_aborted())
                    },
                )?;
            }
        }
        let mut effects = MatchAwareLaneEffects {
            program,
            engine: &mut engine,
            lane,
            governor,
            or_passes: masks.or_passes,
            row: absolute_row,
            candidate_start,
            candidate_bound,
            eligible,
            can_accept,
        };
        if direct {
            // On the ordered-sibling route each eligible edge reaches acceptance
            // and the compiler proved lower-priority branches may retire. Failed
            // attempts leave the original active registers available to siblings.
            let accepted = if let Some((source, id, edge)) = only_edge {
                effects.apply::<true>(None, source, id, edge)?
            } else {
                let source = effects
                    .lane
                    .active_state(0)
                    .expect("one active lane")
                    .state_id;
                let mut accepted = false;
                for id in program.transitions.sealed_range(source) {
                    let edge = program.transitions.sealed_edge(id);
                    effects
                        .governor
                        .record_completed(1, || matcher.is_aborted())?;
                    if eligible & (1 << edge.symbol_id.index()) != 0
                        && effects.apply::<true>(Some(0), source, id, edge)?
                    {
                        accepted = true;
                        break;
                    }
                }
                accepted
            };
            if !accepted {
                effects
                    .governor
                    .record_completed(1, || matcher.is_aborted())?;
                effects.lane.finish_row();
            }
            record_direct_candidate(effects.lane, &mut self.collection.routes.direct);
            scan_state.current_row = current_row + 1;
            return Ok(());
        }
        if let Some((source, id, edge)) = only_edge {
            effects.apply::<false>(None, source, id, edge)?;
        } else {
            effects.advance()?;
        }
        self.finish_row()
    }

    fn finish_row(&mut self) -> Result<()> {
        let matcher = self.matcher;
        let resources = self.session.ctx.resources_mut();
        let lane = resources.lane_scan.as_mut().expect("lane state exists");
        let next_row = resources
            .scan_state
            .current_row
            .checked_add(1)
            .ok_or_else(|| exhausted("row cursor"))?;
        resources
            .scan_state
            .governor
            .record_completed(1, || matcher.is_aborted())?;
        lane.finish_row();
        resources.scan_state.current_row = next_row;
        Ok(())
    }
}

/// A Lane row has a sealed transition order and an immutable active bank.
/// Stage each accepted successor before the outer runner commits the row.
struct MatchAwareLaneEffects<'row, 'program, 'engine, 'state> {
    program: &'program LaneScanProgram,
    engine: &'row mut AggregateEngine<'engine, 'state>,
    lane: &'row mut LaneScanState,
    governor: &'row mut WorkGovernor,
    or_passes: u64,
    row: AbsoluteRow,
    candidate_start: AbsoluteRow,
    candidate_bound: Option<BoundBatchRow<'engine>>,
    eligible: u64,
    can_accept: bool,
}
impl MatchAwareLaneEffects<'_, '_, '_, '_> {
    fn advance(&mut self) -> Result<()> {
        let matcher = self.engine.matcher;
        let transitions = &self.program.transitions;
        for active in 0..self.lane.active_len() {
            let source = self
                .lane
                .active_state(active)
                .ok_or_else(|| invalid("missing lane"))?
                .state_id;
            for edge_id in transitions.sealed_range(source) {
                let edge = transitions.sealed_edge(edge_id);
                self.governor.record_completed(1, || matcher.is_aborted())?;
                if !self.program.requires_partition_end() && edge.after_accept {
                    // A preferred exit already accepted this exact path, and every
                    // remaining edge on this row ranks below it.
                    return Ok(());
                }
                if self.eligible & (1u64 << edge.symbol_id.index()) != 0
                    && self.apply::<false>(Some(active), source, edge_id, edge)?
                {
                    return Ok(());
                }
            }
            self.governor.record_completed(1, || matcher.is_aborted())?;
        }
        Ok(())
    }

    fn apply<const DIRECT: bool>(
        &mut self,
        active: Option<usize>,
        source: AutomatonStateId,
        edge_id: usize,
        edge: OrderedTransitionEdge,
    ) -> Result<bool> {
        let matcher = self.engine.matcher;
        let executable = self.engine.variant;
        let program = self.program;
        let lane = &mut *self.lane;
        let governor = &mut *self.governor;
        let engine = &mut self.engine;
        let candidate_start = self.candidate_start;
        let absolute_row = self.row;
        let payload = if program.payload_symbols & (1u64 << edge.symbol_id.index()) != 0 {
            let user = executable
                .symbol_programs()
                .get(edge.symbol_id.index())
                .expect("sealed lane symbol ID is in the executable program")
                .user()
                .ok_or_else(|| invalid("missing lane evaluator"))?;
            // The match-start cache key does not distinguish packed navigation frames.
            let probe = if lane.active_len() == 1 || program.navigation_layout.is_some() {
                PredicateCacheProbe::Disabled
            } else {
                engine.probe_predicate_cache(
                    user,
                    edge.symbol_id,
                    candidate_start,
                    edge.excluded,
                )
            };
            if probe.cached_decision() == Some(TransitionDecision::Reject) {
                return Ok(false);
            }
            Some((user, probe))
        } else {
            None
        };
        let retains = !program
            .transitions
            .sealed_range(edge.next_state_id)
            .is_empty();

        if DIRECT {
            let work = lane.bind_direct_payload(active.is_some() && payload.is_some());
            governor.record_completed(work, || matcher.is_aborted())?;
        } else if let Some(active) = active {
            let work = lane.prepare_transition(active, retains)?;
            governor.record_completed(work, || matcher.is_aborted())?;
        } else {
            lane.take_single_active();
        }
        engine.state.evaluation.current_match_sequence_number =
            match_sequence_number(candidate_start, absolute_row)?;
        engine.state.evaluation.current_excluded = edge.excluded;
        if let Some((user, probe)) = payload {
            let accumulation = user.accumulation_program();
            let navigation = user.navigation_program();
            let mut work = CoarseWorkCounter::new();
            let mut report_completed_work =
                |units| governor.record_completed(units, || matcher.is_aborted());
            let accumulation_result = vm_executor::execute_vm_accumulation(
                engine,
                lane.scratch_registers_mut(),
                accumulation,
                &mut work,
                &mut report_completed_work,
            );
            work.flush_result(accumulation_result, &mut report_completed_work)?;
            let navigation_result = if navigation.ops().is_empty() {
                Ok(())
            } else {
                let layout = program.navigation_layout.as_deref().ok_or_else(|| {
                    invalid("lane navigation program has no packed layout")
                })?;
                let mut target = layout.view_mut(lane.scratch_navigation_mut())?;
                vm_executor::execute_vm_navigation_stores_into(
                    engine,
                    matcher,
                    edge.symbol_id,
                    |writer, words, is_null| target.apply_update(writer, words, is_null),
                    navigation.ops(),
                    &mut work,
                    &mut report_completed_work,
                )
            };
            work.finish_result(navigation_result, &mut report_completed_work)?;
            let decision = engine.finish_transition_decision(
                edge.symbol_id,
                candidate_start,
                edge.excluded,
                probe,
                self.or_passes & (1u64 << edge.symbol_id.index()) != 0,
                |engine| {
                    let scratch = lane.scratch();
                    let navigation = match program.navigation_layout.as_deref() {
                        Some(layout) => {
                            let frame: PackedNavigationFrameView<'_> =
                                layout.view(scratch.navigation)?;
                            NavigationReadView::Packed(frame)
                        }
                        None => NavigationReadView::Empty,
                    };
                    // Clean private classification can leave shifted columns
                    // unmaterialized. Consult it before the bound-input shortcut.
                    if let Some(classification) = &matcher.program.classification
                        && let Ok((batch, row)) = engine.input_row()
                        && let Some(accepted) =
                            classification.cached_demand(batch, row, edge.symbol_id)
                    {
                        governor.record_completed(1, || matcher.is_aborted())?;
                        return Ok(if accepted {
                            TransitionDecision::AcceptFinal
                        } else {
                            TransitionDecision::Reject
                        });
                    }
                    let predicate = match user.evaluator() {
                        ExecutableSymbolEvaluator::Static => {
                            return Ok(TransitionDecision::AcceptFinal);
                        }
                        ExecutableSymbolEvaluator::Incremental(
                            ExecutableIncrementalEvaluator::Direct { predicate, .. },
                        ) => predicate,
                        _ => {
                            return datafusion_common::internal_err!(
                                "MATCH_RECOGNIZE lane evaluation requires a static or direct evaluator"
                            );
                        }
                    };
                    if let Some(current_bound) = engine.bound_row
                        && let Some(ops) = predicate.direct_loop_work()
                    {
                        let direct_row = DirectRow {
                            current: Some(current_bound),
                            candidate_start: self.candidate_bound,
                            sequence: engine
                                .state
                                .evaluation
                                .current_match_sequence_number,
                            match_number: engine.next_match_number,
                        };
                        if let Some(accepted) = predicate.evaluate_direct_row(
                            direct_row,
                            scratch.registers,
                            navigation,
                        ) {
                            governor.record_completed(ops, || matcher.is_aborted())?;
                            return Ok(if accepted {
                                TransitionDecision::AcceptFinal
                            } else {
                                TransitionDecision::Reject
                            });
                        }
                    }
                    engine.evaluate_direct_predicate(
                        scratch.registers,
                        navigation,
                        edge.symbol_id,
                        predicate,
                        &mut |units| {
                            governor.record_completed(units, || matcher.is_aborted())
                        },
                    )
                },
            )?;
            match decision {
                TransitionDecision::AcceptFinal => {}
                TransitionDecision::Reject => return Ok(false),
                TransitionDecision::CheckHistory => {
                    return datafusion_common::internal_err!(
                        "MATCH_RECOGNIZE lane evaluator cannot request Deferred evaluation"
                    );
                }
            }
        }
        if executable.requires_position_offset() {
            checked_position_offset(candidate_start, absolute_row)?;
        }
        if DIRECT {
            lane.advance_direct_edge(edge_id, absolute_row, governor, || {
                matcher.is_aborted()
            })?;
            #[cfg(test)]
            if let Some(metrics) = &matcher.services.metrics {
                metrics.accepted_edges.add(1);
            }
            return Ok(true);
        }
        lane.apply_scratch_transition(source, edge_id, absolute_row)?;
        let row_complete = commit_scratch_transition(
            matcher,
            executable.automaton(),
            lane,
            absolute_row,
            retains,
            self.can_accept,
            &mut |units| governor.record_completed(units, || matcher.is_aborted()),
        )?;
        #[cfg(test)]
        if let Some(metrics) = &matcher.services.metrics {
            metrics.accepted_edges.add(1);
        }
        Ok(row_complete)
    }
}

fn record_direct_candidate(lane: &mut LaneScanState, direct: &mut usize) {
    if lane.direct == DirectScan::Ready {
        lane.direct = DirectScan::Running;
        *direct += 1;
    }
}

fn match_sequence_number(start: AbsoluteRow, row: AbsoluteRow) -> Result<i64> {
    row.checked_offset_from(start)
        .and_then(|steps| steps.as_u64().checked_add(1))
        .and_then(|value| i64::try_from(value).ok())
        .ok_or_else(|| exhausted("match sequence number"))
}

fn exhausted(label: &str) -> DataFusionError {
    DataFusionError::ResourcesExhausted(format!(
        "MATCH_RECOGNIZE lane {label} is too large to represent"
    ))
}

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

#[test]
fn staged_successor_still_demands_a_fallible_define() {
    use crate::core::{
        NormalizedPattern, Pattern, Symbol, SymbolEvalMode, SymbolId, vm::RegisterLayout,
    };
    use crate::execution::common::memory::new_unbounded_state_memory;
    use crate::execution::matching::program::contracts::SymbolProgramTable;
    use crate::execution::matching::{
        build_test_matcher, deterministic_test_config, predicate_test_helper,
        test_user_symbol_program,
    };
    use crate::execution::storage::collection::BatchCollection;
    use datafusion::arrow::array::{ArrayRef, BooleanArray, RecordBatch};
    use datafusion::scalar::ScalarValue;
    use datafusion_expr::lit;
    use datafusion_physical_expr::expressions::Literal;

    let pattern = NormalizedPattern::Ast(Pattern::Concat(vec![
        Pattern::Symbol(Symbol::Named("A".into())),
        Pattern::Symbol(Symbol::Named("B".into())),
    ]));
    let compiled = Arc::new(
        CompiledAutomaton::compile(&pattern, &["A".into(), "B".into()]).unwrap(),
    );
    let id = |index| SymbolId::try_new(index, compiled.num_symbols()).unwrap();
    let programs = SymbolProgramTable::try_new(
        vec![
            test_user_symbol_program(
                id(1),
                SymbolEvalMode::Incremental,
                Some(Arc::new(Literal::new(ScalarValue::Boolean(Some(true))))),
                None,
                vec![],
                Some(predicate_test_helper::compile(
                    (lit(ScalarValue::DurationNanosecond(Some(i64::MAX)))
                        + lit(ScalarValue::DurationNanosecond(Some(1))))
                    .eq(lit(ScalarValue::DurationNanosecond(Some(1)))),
                    &[],
                    vec![],
                )),
            ),
            test_user_symbol_program(
                id(2),
                SymbolEvalMode::Static,
                None,
                None,
                vec![],
                None,
            ),
        ],
        RegisterLayout::empty_compact(0),
    )
    .unwrap();
    let batch = RecordBatch::try_from_iter([(
        "__mr_symbol_b",
        Arc::new(BooleanArray::from(vec![true])) as ArrayRef,
    )])
    .unwrap();
    let schema = batch.schema();
    let matcher = build_test_matcher(
        Arc::clone(&schema),
        pattern,
        compiled,
        &deterministic_test_config(),
        |input| input.symbols.symbol_programs = programs,
    )
    .unwrap();
    let collection = BatchCollection::try_new(vec![batch], schema).unwrap();
    let executable = matcher.program.base_variant();
    let program = executable.lane_scan_program().unwrap();
    let mut lane =
        LaneScanState::try_new(Arc::clone(program), &new_unbounded_state_memory())
            .unwrap();
    let row = AbsoluteRow::ZERO;
    lane.start_candidate(row);
    let source = lane.active_state(0).unwrap().state_id;
    let edge_id = program.transitions.sealed_range(source).start;
    let edge = program.transitions.sealed_edge(edge_id);

    let mut state = Default::default();
    let mut engine = AggregateEngine::new(
        &matcher,
        executable,
        &collection,
        &[],
        &mut state,
        1,
        0,
        0,
        1,
    );
    let bit = 1 << edge.symbol_id.index();
    let mut effects = MatchAwareLaneEffects {
        program,
        engine: &mut engine,
        lane: &mut lane,
        governor: &mut WorkGovernor::default(),
        or_passes: bit,
        row,
        candidate_start: row,
        candidate_bound: None,
        eligible: bit,
        can_accept: true,
    };
    // Stage a passing peer, then demand the same destination without an OR precheck.
    assert!(
        !effects
            .apply::<false>(Some(0), source, edge_id, edge)
            .unwrap()
    );
    assert_eq!(effects.lane.successor_len(), 1);
    effects.or_passes = 0;
    let error = effects
        .apply::<false>(Some(0), source, edge_id, edge)
        .unwrap_err();
    assert!(error.to_string().contains("numeric overflow"), "{error}");
    assert_eq!(effects.lane.successor_len(), 1);
}