datafusion-match-recognize 0.56.1

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
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
// 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 super::super::compiler::resource_layout_with_navigation;
use super::*;
use crate::core::AbsoluteRow;
use crate::core::vm::MAX_REGISTERS;
use crate::core::{NormalizedPattern, Pattern, Symbol, SymbolId};
use crate::execution::matching::row_loop::lane_scan::ir::LaneCapacity;
use crate::execution::matching::row_loop::lane_scan::path::LanePathRun;
use crate::execution::matching::row_loop::ordered_transitions::OrderedTransitionTable;
use crate::nfa::CompiledAutomaton;
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryConsumer, MemoryPool};

fn test_program(
    compiled: &CompiledAutomaton,
    runs: usize,
    optimistic_history: bool,
) -> Arc<LaneScanProgram> {
    let transitions = Arc::new(
        OrderedTransitionTable::try_new(
            compiled,
            &(1..compiled.num_symbols())
                .map(|index| SymbolId::try_new(index, compiled.num_symbols()).unwrap())
                .collect::<Vec<_>>(),
        )
        .unwrap(),
    );
    let (_, _, _, _, bytes) = resource_layout_with_navigation(4, runs, 2, 2).unwrap();
    Arc::new(LaneScanProgram {
        transitions,
        closure_accepting: Arc::clone(compiled.unconditional_first_accepting_state()),
        boundary_anchors:
            crate::execution::matching::row_loop::lane_scan::LaneBoundaryAnchors::None,
        cycle_positions: vec![u64::MAX; compiled.nfa().state_count()].into(),
        cycles: Box::new([]),
        optimistic_history,
        capacity: LaneCapacity {
            live_lanes: 4,
            path_runs_per_lane: runs,
            encoded_program_bytes: 0,
            source_payload_floor_bytes: 0,
            scan_resource_bytes: bytes,
        },

        initial_registers: [0; MAX_REGISTERS],
        register_words: 2,
        navigation_layout: None,
        navigation_words: 2,
        payload_symbols: 0,
        idempotent_last_symbols: 0,
        suffix_reuse: None,
        direct_linear: false,
        state_meta: Box::new([]),
        direct_edges: Box::new([]),
        direct_payload_work: 1,
    })
}

#[test]
fn lane_banks_preserve_encounter_order_without_shifting_payloads() {
    // Exercise the storage layout independently of graph capacity inference.
    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into()))),
        &["A".into()],
    )
    .unwrap();
    let program = test_program(&compiled, 2, false);
    let bytes = program.capacity.scan_resource_bytes;
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(bytes));
    let memory = Arc::new(MemoryConsumer::new("lane-banks").register(&pool));
    let mut lane = LaneScanState::try_new(program, &memory).unwrap();
    lane.start_candidate(AbsoluteRow::new(0));
    let assert_payload = |view: LaneView<'_>, tag: u64| {
        assert_eq!(view.registers, &[tag, tag + 1]);
        assert_eq!(view.navigation, &[tag + 2, tag + 3]);
        assert_eq!(view.state.history_runs, 1);
        assert_eq!(view.history, &[LanePathRun::edge(0, AbsoluteRow::new(tag))]);
    };
    use LaneSuccessorAction::{Append, Discard};
    for expected in [[0, 1, 2, 3], [0, 1, 2, 3]] {
        let actions = [Append; 4];
        for (tag, action) in actions.into_iter().enumerate() {
            let tag = tag as u64;
            lane.scratch_registers_mut()
                .copy_from_slice(&[tag, tag + 1]);
            lane.scratch_navigation_mut()
                .copy_from_slice(&[tag + 2, tag + 3]);
            let slot = lane.scratch_slot();
            lane.lanes[slot].history_runs = 1;
            let history = lane.history_range(slot);
            lane.histories[history.start] = LanePathRun::edge(0, AbsoluteRow::new(tag));
            let publication = lane
                .plan_publication(action, None, AbsoluteRow::new(0))
                .unwrap();
            assert_eq!(publication.work, 7, "one payload copy and publication");
            lane.publish_scratch(publication);
        }
        for (index, tag) in expected.into_iter().enumerate() {
            assert_payload(lane.successor(index).unwrap(), tag);
        }
        let error = lane
            .plan_publication(Append, None, AbsoluteRow::ZERO)
            .err()
            .expect("a full bank must request the generic route");
        assert!(is_lane_capacity_miss(&error));
        // Discarding a lower-priority peer at full capacity leaves every slot intact.
        let publication = lane
            .plan_publication(Discard, None, AbsoluteRow::ZERO)
            .unwrap();
        lane.publish_scratch(publication);
        lane.finish_row();
        assert_eq!(lane.active_len(), 4);
        assert_eq!(lane.successor_len(), 0);
        for (index, tag) in expected.into_iter().enumerate() {
            assert_payload(lane.active(index).unwrap(), tag);
            assert_eq!(lane.prepare_transition(index, false).unwrap(), 6);
            assert_payload(lane.scratch(), tag);
        }
        assert_eq!(pool.reserved(), bytes);
    }
    lane.discard_candidate();
    assert!(!lane.selection_is_open());
    lane.start_candidate(AbsoluteRow::new(10));
    assert_eq!(lane.active_len(), 1);
    assert_eq!(lane.active(0).unwrap().registers, &[0, 0]);
    lane.prepare_transition(0, false).unwrap();
    let scratch = lane.scratch_slot();
    lane.lanes[scratch].history_runs = 2;
    let histories = lane.histories.clone();
    let error = lane
        .apply_scratch_transition(compiled.nfa().start_state(), 0, AbsoluteRow::new(10))
        .unwrap_err();
    assert!(is_lane_capacity_miss(&error));
    assert_eq!(
        lane.histories, histories,
        "a capacity miss cannot overwrite history"
    );
    assert!(!is_lane_capacity_miss(&DataFusionError::Execution(
        "ordinary SQL error".into()
    )));
    // A failed predicate may have already changed the proposed register and
    // navigation values. The next edge must start from the untouched source.
    lane.discard_candidate();
    lane.start_candidate(AbsoluteRow::new(11));
    lane.prepare_transition(0, true).unwrap();
    lane.scratch_registers_mut()[0] = 41;
    lane.scratch_navigation_mut()[0] = 42;
    assert_eq!(lane.successor_len(), 0);
    lane.prepare_transition(0, true).unwrap();
    assert_eq!(lane.scratch().registers, &[0, 0]);
    assert_eq!(lane.scratch().navigation, &[0, 0]);
    lane.scratch_registers_mut()[0] = 7;
    let publish = lane
        .plan_publication(Append, None, AbsoluteRow::new(11))
        .unwrap();
    assert_eq!(
        publish.work, 1,
        "the prepared successor needs only publication"
    );
    lane.publish_scratch(publish);
    // A rejected sibling cannot overwrite the already staged successor.
    lane.prepare_transition(0, true).unwrap();
    lane.scratch_registers_mut()[0] = 99;
    assert_eq!(lane.successor(0).unwrap().registers, &[7, 0]);
    lane.finish_row();
    assert_eq!(lane.active(0).unwrap().registers, &[7, 0]);
    // Once no sibling can visit the source, its registers and navigation stay
    // in their physical slot across an accepted step. A rejected later step
    // cannot republish that slot or leak its contents into the next candidate.
    lane.take_single_active();
    let owned = lane.scratch_slot();
    assert_eq!(lane.active_len(), 0);
    lane.scratch_navigation_mut()[0] = 19;
    let publication = lane
        .plan_publication(Append, None, AbsoluteRow::new(12))
        .unwrap();
    assert_eq!(publication.work, 1);
    lane.publish_scratch(publication);
    lane.finish_row();
    assert_eq!(lane.active(0).unwrap().navigation, &[19, 0]);

    // No staged bank separates a sole continuation from the live payload.
    // A discontinuity must leave the exact previous history and payload usable.
    let source = lane.active(0).unwrap().state.state_id;
    let edge = lane.program.transitions.sealed_range(source).start;
    assert!(
        lane.advance_single_active(source, edge, AbsoluteRow::new(12))
            .is_err()
    );
    assert!(lane.active(0).unwrap().history.is_empty());
    lane.advance_single_active(source, edge, AbsoluteRow::new(11))
        .unwrap();
    let active = lane.active(0).unwrap();
    assert_eq!(active.history[0].first_row(), AbsoluteRow::new(11));
    assert_eq!(active.registers, &[7, 0]);
    assert_eq!(active.navigation, &[19, 0]);
    assert!(lane.is_at_row_boundary());
    assert_eq!(pool.reserved(), bytes);

    lane.take_single_active();
    assert_eq!(lane.scratch_slot(), owned);
    lane.scratch_registers_mut()[0] = 43;
    lane.finish_row();
    assert_eq!(lane.active_len(), 0);
    lane.start_candidate(AbsoluteRow::new(13));
    assert_eq!(lane.active(0).unwrap().navigation, &[0, 0]);
    assert_eq!(lane.active(0).unwrap().registers, &[0, 0]);
    drop(lane);
    assert_eq!(pool.reserved(), 0);
}

#[test]
fn direct_linear_rejection_and_winning_prefix_match_staged_publication() -> Result<()> {
    use crate::config::CancellationPolicy;
    use crate::core::{PhysicalRowCount, RepetitionQuantifier};
    use crate::execution::common::work::WorkGovernor;

    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Repetition(
            Box::new(Pattern::Alternation(vec![
                Pattern::Symbol(Symbol::Named("A".into())),
                Pattern::Exclude(Symbol::Named("B".into())),
            ])),
            RepetitionQuantifier::OneOrMore,
        )),
        &["A".into(), "B".into()],
    )?;
    let program = test_program(&compiled, 8, true);
    let bytes = program.capacity.scan_resource_bytes;
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(bytes * 2));
    let memory = MemoryConsumer::new("direct-linear-winner").register(&pool);
    let mut direct = LaneScanState::try_new(Arc::clone(&program), &memory)?;
    let mut staged = LaneScanState::try_new(Arc::clone(&program), &memory)?;
    let start = AbsoluteRow::new(17);
    direct.start_candidate(start);
    staged.start_candidate(start);
    let mut governor = WorkGovernor::default();
    governor.bind_cancellation_policy(
        CancellationPolicy::try_from_configured(1, 0).unwrap(),
    )?;

    // Two symbol changes plus an extended compressed run. Advance both
    // publishers along the same physical path and compare the complete winner.
    for (index, symbol) in [1, 2, 2, 2, 1].into_iter().enumerate() {
        let row = start
            .checked_add(PhysicalRowCount::new(index as u64))
            .unwrap();
        let source = direct.active_state(0).unwrap().state_id;
        let id = program
            .transitions
            .sealed_range(source)
            .find(|&id| program.transitions.sealed_edge(id).symbol_id.index() == symbol)
            .unwrap();
        let edge = program.transitions.sealed_edge(id);
        // Reject a preferred sibling after tentative writes to both value frames.
        direct.bind_direct_payload(true);
        direct.scratch_registers_mut()[0] = u64::MAX;
        direct.scratch_navigation_mut()[0] = u64::MAX;
        direct.bind_direct_payload(true);
        staged.prepare_transition(0, true)?;
        assert_eq!(direct.scratch().registers, staged.scratch().registers);
        assert_eq!(direct.scratch().navigation, staged.scratch().navigation);
        for lane in [&mut direct, &mut staged] {
            lane.scratch_registers_mut()[0] += index as u64 + 1;
            lane.scratch_navigation_mut()[0] = row.as_u64();
        }

        let before = direct.incumbent();
        assert!(
            direct
                .advance_direct_edge(id, row, &mut governor, || true)
                .unwrap_err()
                .to_string()
                .contains("cancelled")
        );
        assert_eq!(direct.incumbent(), before);
        direct.advance_direct_edge(id, row, &mut governor, || false)?;
        staged.apply_scratch_transition(source, id, row)?;
        let accepting = program.closure_accepting[edge.next_state_id.index()].unwrap();
        let publication = staged.plan_publication(
            LaneSuccessorAction::Append,
            Some((
                accepting,
                row.checked_add(PhysicalRowCount::new(1)).unwrap(),
            )),
            row,
        )?;
        staged.publish_scratch(publication);
        staged.finish_row();
        assert_eq!(direct.incumbent(), staged.incumbent());
        let actual = direct.incumbent_view().unwrap();
        let expected = staged.incumbent_view().unwrap();
        assert_eq!(actual.registers, expected.registers);
        assert_eq!(actual.navigation, expected.navigation);
        assert_eq!(actual.history, expected.history);
        assert_eq!(pool.reserved(), 2 * bytes);
    }
    drop((direct, staged));
    assert_eq!(pool.reserved(), 0);
    Ok(())
}

#[test]
fn direct_terminal_winner_slot_isolated_from_next_candidates_rejected_edge() -> Result<()>
{
    use crate::core::RepetitionQuantifier;
    use crate::execution::common::work::WorkGovernor;

    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Concat(vec![
            Pattern::Symbol(Symbol::Named("A".into())),
            Pattern::Repetition(
                Box::new(Pattern::Symbol(Symbol::Named("B".into()))),
                RepetitionQuantifier::AtMostOne,
            ),
        ])),
        &["A".into(), "B".into()],
    )?;
    let program = test_program(&compiled, 2, false);
    let bytes = program.capacity.scan_resource_bytes;
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(bytes));
    let memory = MemoryConsumer::new("terminal-winner").register(&pool);
    let mut lane = LaneScanState::try_new(Arc::clone(&program), &memory)?;
    let mut governor = WorkGovernor::default();

    let edge_id = |lane: &LaneScanState, symbol| {
        let source = lane.active_state(0).unwrap().state_id;
        program
            .transitions
            .sealed_range(source)
            .find(|&id| program.transitions.sealed_edge(id).symbol_id.index() == symbol)
            .unwrap()
    };
    for (start, accept_b) in [(10, true), (20, false)] {
        let row_a = AbsoluteRow::new(start);
        let row_b = AbsoluteRow::new(start + 1);
        lane.start_candidate(row_a);
        assert!(lane.incumbent().is_none());
        let active = lane.active(0).unwrap();
        assert!(active.history.is_empty());
        assert_eq!(active.registers, &[0, 0]);
        assert_eq!(active.navigation, &[0, 0]);
        let active_slot = (active.registers.as_ptr(), active.navigation.as_ptr());

        let a = edge_id(&lane, 1);
        lane.bind_direct_payload(false);
        lane.scratch_registers_mut().copy_from_slice(&[start, 1]);
        lane.scratch_navigation_mut()
            .copy_from_slice(&[start, start]);
        lane.advance_direct_edge(a, row_a, &mut governor, || false)?;
        let early = lane.incumbent().unwrap();
        let b = edge_id(&lane, 2);
        let winner = lane.incumbent_view().unwrap();
        let early_slot = (winner.registers.as_ptr(), winner.navigation.as_ptr());
        assert_ne!(early_slot, active_slot);
        assert_eq!(early.end_row, row_a);
        assert_eq!(winner.history, &[LanePathRun::edge(a, row_a)]);

        // B is the sole continuation and its DEFINE updates both live frames
        // before its predicate decides whether the winner extends beyond A.
        lane.bind_direct_payload(false);
        lane.scratch_registers_mut()
            .copy_from_slice(&[start + 9, 2]);
        lane.scratch_navigation_mut()[1] = row_b.as_u64();
        if accept_b {
            lane.advance_direct_edge(b, row_b, &mut governor, || false)?;
        } else {
            lane.finish_row();
            assert_eq!(lane.incumbent(), Some(early));
        }
        assert_eq!(lane.active_len(), 0);
        let winner = lane.incumbent_view().unwrap();
        assert_eq!(
            (winner.registers.as_ptr(), winner.navigation.as_ptr()),
            if accept_b { active_slot } else { early_slot }
        );
        let (registers, navigation, end) = if accept_b {
            ([start + 9, 2], [start, start + 1], row_b)
        } else {
            ([start, 1], [start, start], row_a)
        };
        assert_eq!(winner.registers, &registers);
        assert_eq!(winner.navigation, &navigation);
        let selected = lane.selected_runs()?;
        assert_eq!((selected.start, selected.end), (row_a, end));
        let expected = [LanePathRun::edge(a, row_a), LanePathRun::edge(b, row_b)];
        let count = if accept_b { 2 } else { 1 };
        assert_eq!(winner.history, &expected[..count]);
        assert_eq!(selected.history()?.runs.len(), count);
        for i in 0..count {
            let (edge, _) = selected.history()?.edge_and_period(i, 0)?;
            assert_eq!(edge.symbol_id.index(), i + 1);
        }
        lane.discard_candidate();
    }
    drop(lane);
    assert_eq!(pool.reserved(), 0);
    Ok(())
}

#[test]
fn consecutive_starts_reuse_the_admitted_banks_with_fresh_payloads() -> Result<()> {
    use crate::execution::matching::row_loop::continuation::ScanResources;

    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into()))),
        &["A".into()],
    )?;
    let program = test_program(&compiled, 2, false);
    let bytes = program.capacity.scan_resource_bytes;
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(2 * bytes - 1));
    let reservation =
        Arc::new(MemoryConsumer::new("consecutive lane starts").register(&pool));
    let mut resources = ScanResources::try_new(
        compiled.nfa().state_count(),
        compiled.num_symbols(),
        reservation,
    )?;
    let baseline = pool.reserved();
    let mut backing = None;
    for start in 0..16 {
        resources.prepare_lane_scan(&program, AbsoluteRow::new(start))?;
        let lane = resources.lane_scan.as_mut().unwrap();
        let initial = lane.active(0).unwrap();
        assert_eq!(initial.history, &[]);
        assert_eq!(initial.registers, &[0, 0]);
        assert_eq!(initial.navigation, &[0, 0]);
        let addresses = (
            initial.registers.as_ptr(),
            initial.navigation.as_ptr(),
            lane.histories.as_ptr(),
        );
        assert_eq!(*backing.get_or_insert(addresses), addresses);
        assert_eq!(pool.reserved(), baseline + bytes);
        lane.bind_direct_payload(false);
        lane.scratch_registers_mut()[0] = 17;
        lane.scratch_navigation_mut()[1] = 29;
        lane.discard_candidate();
    }
    drop(resources);
    assert_eq!(pool.reserved(), 0);
    Ok(())
}

#[test]
fn saturated_root_fork_skips_direct_tables() -> Result<()> {
    use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;

    let branches =
        vec![Pattern::Symbol(Symbol::Named("A".into())); COARSE_WORK_BATCH_SIZE];
    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Alternation(branches)),
        &["A".into()],
    )?;
    let mut program = test_program(&compiled, 2, false);
    let program = Arc::get_mut(&mut program).unwrap();
    assert_eq!(
        program
            .transitions
            .sealed_range(compiled.nfa().start_state())
            .len(),
        COARSE_WORK_BATCH_SIZE
    );
    program.direct_linear = true;
    program.seal_direct_states(&compiled, usize::MAX)?;
    assert!(program.state_meta.is_empty());
    assert!(program.direct_edges.is_empty());
    Ok(())
}

#[test]
fn a_single_root_edge_must_fit_the_continuous_budget() -> Result<()> {
    use crate::execution::common::{
        progress::COARSE_WORK_BATCH_SIZE, work::WorkGovernor,
    };

    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into()))),
        &["A".into()],
    )?;
    for extra in [0, 1] {
        let mut program = test_program(&compiled, 2, false);
        let p = Arc::get_mut(&mut program).unwrap();
        p.direct_linear = true;
        p.payload_symbols = 0b10;
        p.direct_payload_work = 0;
        let budget = COARSE_WORK_BATCH_SIZE + extra;
        p.direct_payload_work =
            u8::try_from(budget - p.direct_row_bound(1, 1, 1)).unwrap();
        assert_eq!(p.direct_row_bound(1, 1, 1), budget);
        p.seal_direct_states(&compiled, usize::MAX)?;
        assert_eq!(p.supports_direct_loop(), extra == 0);

        // Ordinary Lane can still consume the edge and select its winner.
        let edge = p
            .transitions
            .sealed_range(compiled.nfa().start_state())
            .start;
        let pool: Arc<dyn MemoryPool> =
            Arc::new(GreedyMemoryPool::new(p.capacity.scan_resource_bytes));
        let memory = MemoryConsumer::new("single root edge").register(&pool);
        let mut lane = LaneScanState::try_new(program, &memory)?;
        lane.start_candidate(AbsoluteRow::ZERO);
        lane.bind_direct_payload(true);
        lane.advance_direct_edge(
            edge,
            AbsoluteRow::ZERO,
            &mut WorkGovernor::default(),
            || false,
        )?;
        assert!(lane.incumbent().is_some());
    }
    Ok(())
}

#[test]
fn direct_state_metadata_respects_encoded_capacity_and_partial_row_work() -> Result<()> {
    use super::super::{DirectLinearCursor, DirectLinearStep, DirectScratch};

    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Alternation(vec![
            Pattern::Symbol(Symbol::Named("A".into())),
            Pattern::Symbol(Symbol::Named("B".into())),
        ])),
        &["A".into(), "B".into()],
    )?;
    let mut program = test_program(&compiled, 4, false);
    let program = Arc::get_mut(&mut program).unwrap();
    program.payload_symbols = 0b110;
    program.direct_linear = true;
    program.direct_payload_work = 40; // One edge fits; both together exceed the row budget.
    program.seal_direct_states(&compiled, 1)?;
    assert!(!program.supports_direct_loop());
    assert_eq!(program.capacity.encoded_program_bytes, 0);
    program.seal_direct_states(&compiled, usize::MAX)?;
    assert_eq!(
        program.capacity.encoded_program_bytes,
        size_of_val(program.state_meta.as_ref())
            + size_of_val(program.direct_edges.as_ref())
    );

    let mut cursor =
        DirectLinearCursor::new(program, compiled.nfa().start_state(), usize::MAX - 1)
            .unwrap();
    let mut scratch = DirectScratch::default();
    let mut work = 0;
    assert_eq!(
        cursor.step::<false>(
            program,
            0b110,
            false,
            &mut scratch,
            &mut work,
            |_, _, _| panic!("over-budget row evaluated a DEFINE")
        )?,
        DirectLinearStep::Handoff
    );
    let mut work = 0;
    assert_eq!(
        cursor.step::<false>(
            program,
            0b010,
            false,
            &mut scratch,
            &mut work,
            |edge, _, _| Ok(Some(edge.symbol_id.index() == 1))
        )?,
        DirectLinearStep::Finished
    );
    assert!(work <= crate::execution::common::progress::COARSE_WORK_BATCH_SIZE);
    let (winner, _) = cursor.winner::<false>(program)?.unwrap();
    assert_eq!(winner.acceptance.as_u64(), usize::MAX as u64);
    Ok(())
}

#[test]
fn inline_cursor_preserves_sibling_demand_and_the_winners_register_words() -> Result<()> {
    use super::super::{DirectLinearCursor, DirectLinearStep, DirectScratch};
    use crate::core::RepetitionQuantifier;

    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Repetition(
            Box::new(Pattern::Alternation(vec![
                Pattern::Symbol(Symbol::Named("A".into())),
                Pattern::Exclude(Symbol::Named("B".into())),
            ])),
            RepetitionQuantifier::OneOrMore,
        )),
        &["A".into(), "B".into()],
    )?;
    let mut program = test_program(&compiled, 8, true);
    let program = Arc::get_mut(&mut program).unwrap();
    program.direct_linear = true;
    program.payload_symbols = 0b110;
    program.seal_direct_states(&compiled, usize::MAX)?;
    let mut scratch = DirectScratch::default();
    program.initial_registers[0] = 17;
    let initial = compiled.nfa().start_state();
    let start = 12;
    let mut cursor = DirectLinearCursor::new(program, initial, start).unwrap();
    let mut work = 0;
    let mut seen = Vec::new();
    assert_eq!(
        cursor.step::<true>(
            program,
            0b110,
            false,
            &mut scratch,
            &mut work,
            |edge, regs, _| {
                assert_eq!(regs[0], 17);
                regs[0] = 999;
                seen.push(edge.symbol_id.index());
                Ok(Some(true))
            }
        )?,
        DirectLinearStep::Ambiguous
    );
    assert_eq!(seen, [1, 2]);
    assert_eq!(cursor.next_row(), start);
    assert!(cursor.winner::<true>(program)?.is_none());
    cursor.reset::<true>(program, initial, start);
    assert_eq!(
        cursor.step::<true>(
            program,
            0b110,
            true,
            &mut scratch,
            &mut work,
            |edge, _, _| {
                assert_eq!(
                    edge.symbol_id.index(),
                    1,
                    "lower demand escaped a proved retirement"
                );
                Ok(Some(true))
            }
        )?,
        DirectLinearStep::Advanced
    );
    cursor.reset::<true>(program, initial, start);
    assert_eq!(
        cursor.step::<true>(
            program,
            0b110,
            false,
            &mut scratch,
            &mut work,
            |edge, _, _| {
                if edge.symbol_id.index() == 2 {
                    return Err(DataFusionError::Execution(
                        "canonical evaluator must decide".into(),
                    ));
                }
                Ok(Some(true))
            }
        )?,
        DirectLinearStep::Handoff
    );
    assert_eq!(cursor.next_row(), start);
    assert!(cursor.winner::<true>(program)?.is_none());
    cursor.reset::<true>(program, initial, start);
    work = 0;
    let bound = cursor.step_work_bound(program);
    let mut visited = Vec::new();
    assert_eq!(
        cursor.step::<true>(
            program,
            0b110,
            false,
            &mut scratch,
            &mut work,
            |edge, regs, nav| {
                let id = edge.symbol_id.index();
                visited.push(id);
                assert_eq!(regs, &[17, 0]);
                assert_eq!(nav, &[0, 0]);
                regs[0] = id as u64;
                nav[0] = 10 + id as u64;
                Ok(Some(id == 2))
            }
        )?,
        DirectLinearStep::Advanced
    );
    assert_eq!(visited, [1, 2]);
    assert!(work > 0 && work <= bound);
    let next = cursor.next_row();
    assert_eq!(next, 13);
    let mut rejected_siblings = Vec::new();
    assert_eq!(
        cursor.step::<true>(
            program,
            0b110,
            false,
            &mut scratch,
            &mut work,
            |edge, regs, nav| {
                let id = edge.symbol_id.index();
                rejected_siblings.push(id);
                assert_eq!(regs, &[2, 0]);
                assert_eq!(nav, &[12, 0]);
                regs[0] = 90 + id as u64;
                nav[0] = 900 + id as u64;
                Ok(Some(false))
            }
        )?,
        DirectLinearStep::Finished
    );
    assert_eq!(rejected_siblings, [1, 2]);
    let (winner, regs) = cursor.winner::<true>(program)?.unwrap();
    assert_eq!(
        (winner.start, winner.end, winner.acceptance),
        (
            AbsoluteRow::new(12),
            AbsoluteRow::new(12),
            AbsoluteRow::new(13)
        )
    );
    assert_eq!(regs, &[2, 0]);
    cursor.reset::<true>(program, initial, next);
    assert!(cursor.winner::<true>(program)?.is_none());
    assert_eq!(
        cursor.step::<true>(
            program,
            0b010,
            true,
            &mut scratch,
            &mut work,
            |_, regs, nav| {
                assert_eq!(regs, &[17, 0]);
                assert_eq!(nav, &[0, 0]);
                Ok(None)
            }
        )?,
        DirectLinearStep::Handoff
    );
    assert_eq!(cursor.next_row(), next);
    Ok(())
}

#[test]
fn inline_cursor_keeps_the_terminal_siblings_own_words_and_classifier_history()
-> Result<()> {
    check_terminal_sibling::<true>()?;
    check_terminal_sibling::<false>()
}

fn check_terminal_sibling<const TRACK_HISTORY: bool>() -> Result<()> {
    use super::super::{DirectLinearCursor, DirectLinearStep, DirectScratch};
    use crate::core::RepetitionQuantifier;
    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Concat(vec![
            Pattern::Repetition(
                Box::new(Pattern::Symbol(Symbol::Named("J".into()))),
                RepetitionQuantifier::ZeroOrMore,
            ),
            Pattern::Exclude(Symbol::Named("L".into())),
        ])),
        &["J".into(), "L".into()],
    )?;
    let mut program = test_program(&compiled, 8, true);
    let program = Arc::get_mut(&mut program).unwrap();
    program.direct_linear = true;
    program.payload_symbols = 0b110;
    program.seal_direct_states(&compiled, usize::MAX)?;
    let mut scratch = DirectScratch::default();
    let start = 4;
    let mut cursor =
        DirectLinearCursor::new(program, compiled.nfa().start_state(), start).unwrap();
    for (i, (accept_j, accept_l)) in
        [(true, true), (true, true), (true, false), (false, false)]
            .into_iter()
            .enumerate()
    {
        let mut work = 0;
        let bound = cursor.step_work_bound(program);
        let mut seen = Vec::new();
        let outcome = cursor.step::<TRACK_HISTORY>(
            program,
            0b110,
            false,
            &mut scratch,
            &mut work,
            |edge, regs, nav| {
                let symbol = edge.symbol_id.index();
                seen.push(symbol);
                assert_eq!(regs[0], 4 * i as u64);
                assert_eq!(nav[0], i as u64);
                nav[0] += 1;
                regs[0] += if symbol == 1 { 4 } else { 8 };
                Ok(Some(if symbol == 1 { accept_j } else { accept_l }))
            },
        )?;
        assert_eq!(seen, [1, 2]);
        assert!(work <= bound);
        assert_eq!(
            outcome,
            if accept_j {
                DirectLinearStep::Advanced
            } else {
                DirectLinearStep::Finished
            }
        );
    }
    let (winner, regs) = cursor.winner::<TRACK_HISTORY>(program)?.unwrap();
    assert_eq!(
        (winner.start, winner.end, winner.acceptance),
        (
            AbsoluteRow::new(4),
            AbsoluteRow::new(5),
            AbsoluteRow::new(6)
        )
    );
    assert_eq!(regs[0], 12);
    if !TRACK_HISTORY {
        assert!(winner.runs.is_none());
        return Ok(());
    }
    let history = winner.history()?;
    assert_eq!(history.runs.len(), 2);
    let (j, _) = history.edge_and_period(0, 0)?;
    let (l, _) = history.edge_and_period(1, 0)?;
    assert_eq!((j.symbol_id.index(), j.excluded), (1, false));
    assert_eq!((l.symbol_id.index(), l.excluded), (2, true));
    Ok(())
}

#[test]
fn bitset_probe_rejects_without_committing_and_defers_acceptance() -> Result<()> {
    use super::super::{DirectLinearCursor, StaticProbe};
    use crate::core::RepetitionQuantifier;
    let symbol = |s: &str| Pattern::Symbol(Symbol::Named(s.into()));
    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Concat(vec![
            Pattern::Repetition(
                Box::new(Pattern::Alternation(vec![symbol("A"), symbol("B")])),
                RepetitionQuantifier::OneOrMore,
            ),
            symbol("C"),
        ])),
        &["A".into(), "B".into(), "C".into()],
    )?;
    let mut program = test_program(&compiled, 8, true);
    let program = Arc::get_mut(&mut program).unwrap();
    program.direct_linear = true;
    program.seal_direct_states(&compiled, usize::MAX)?;
    let cursor =
        DirectLinearCursor::new(program, compiled.nfa().start_state(), 0).unwrap();
    for (words, expected) in [
        (vec![6, 6, 0], StaticProbe::NoMatch(2)),
        (vec![6, 6, 8], StaticProbe::FoundWinner),
        (vec![6, 6, 6], StaticProbe::Boundary(3)),
    ] {
        let mut work = 0;
        assert_eq!(
            cursor.probe_static_bitset_reject(
                program,
                words.len(),
                |r| words[r],
                &mut work,
                |_, _| Ok(false)
            )?,
            expected
        );
        assert!(work > 0);
        assert_eq!(cursor.next_row(), 0);
        assert!(cursor.has_no_winner());
    }
    let mut work = 0;
    assert_eq!(
        cursor.probe_static_bitset_reject(
            program,
            8,
            |_| 6,
            &mut work,
            |work, _| Ok(*work != 0)
        )?,
        StaticProbe::Yield
    );
    // A guarded acceptance edge is outside the reject-only proof.
    program.direct_edges[0].flags |= super::super::ir::DirectEdge::AFTER_ACCEPT;
    assert_eq!(
        cursor.probe_static_bitset_reject(program, 8, |_| 6, &mut 0, |_, _| Ok(false))?,
        StaticProbe::NeedLane
    );
    Ok(())
}

#[test]
fn idempotent_last_coalesces_runs_and_unbound_callback_leaves_cursor_unchanged()
-> Result<()> {
    use super::super::{DirectLinearCursor, DirectLinearStep};
    use crate::core::RepetitionQuantifier;
    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Repetition(
            Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
            RepetitionQuantifier::OneOrMore,
        )),
        &["A".into()],
    )?;
    let mut program = test_program(&compiled, 8, true);
    let program = Arc::get_mut(&mut program).unwrap();
    program.direct_linear = true;
    program.payload_symbols = 2;
    program.idempotent_last_symbols = 2;
    program.seal_direct_states(&compiled, usize::MAX)?;
    let mut cursor =
        DirectLinearCursor::new(program, compiled.nfa().start_state(), 0).unwrap();
    let memory = crate::execution::common::memory::new_unbounded_state_memory();
    cursor.configure_history(super::super::ClassifierDemand::All, &memory)?;
    let mut work = 0;
    assert_eq!(
        cursor.step_static_packed::<true>(
            program,
            &[2; 12],
            0,
            true,
            64,
            &mut work,
            |_, _, nav| {
                nav[0] = 999;
                Ok(None)
            }
        )?,
        None
    );
    assert_eq!(cursor.next_row(), 0);
    assert!(cursor.has_no_winner());
    assert_eq!(work, 0);
    let mut writes = Vec::new();
    while cursor.next_row() < 12 {
        assert_eq!(
            cursor.step_static_packed::<true>(
                program,
                &[2; 12][..12 - cursor.next_row()],
                0,
                true,
                64,
                &mut work,
                |sym, row, nav| {
                    assert_ne!(nav[0], 999, "unbound write escaped scratch");
                    writes.push(row);
                    assert_eq!(sym, 1);
                    nav[0] = row as u64;
                    Ok(Some(()))
                }
            )?,
            Some(DirectLinearStep::Advanced)
        );
    }
    assert!(writes.len() < 12);
    assert_eq!(writes.last(), Some(&11));
    assert_eq!(
        work,
        12 + writes.len(),
        "charge rows and each final overwrite"
    );
    // An unbound next row observes the retained endpoint without advancing it.
    let mut retained_last = None;
    assert_eq!(
        cursor.step_static_packed::<true>(
            program,
            &[2],
            0,
            true,
            64,
            &mut work,
            |_, _, nav| {
                retained_last = Some(nav[0]);
                Ok(None)
            }
        )?,
        None
    );
    assert_eq!(retained_last, Some(11));
    assert_eq!(cursor.next_row(), 12);
    assert_eq!(work, 12 + writes.len());
    let (winner, _) = cursor.winner::<true>(program)?.unwrap();
    assert_eq!(winner.end.as_u64(), 11);
    Ok(())
}