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
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
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
// 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.

//! Static input views must preserve logical boundaries and output coordinates
//! when a physical head contains several partitions or a candidate needs history.

use super::{TestPlanSpec, build_test_exec};
use crate::config::MatchRecognizeConfig;
use crate::core::{
    EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeOutputSpec, NavigationOffsets,
    Pattern, RepetitionQuantifier, RowsPerMatch, Symbol,
};
use crate::execution::classification::StaticClassification;
use crate::execution::common::scheduling::SliceControl;
use crate::execution::matching::OutputPartitionBindings;
use crate::execution::physical::PartitionRetention;
use crate::execution::stream::MatchRecognizeStream;
use crate::execution::stream::stateful_stream::match_aware_stream;
use crate::nfa_executor::ExecutePatternInput;
use datafusion::arrow::array::{Array, AsArray, BooleanArray, Int32Array};
use datafusion::arrow::buffer::{BooleanBuffer, NullBuffer};
use datafusion::arrow::datatypes::{DataType, Field, Int32Type, Int64Type, Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::logical_expr::Operator;
use datafusion_common::{Result, ScalarValue};
use datafusion_physical_expr::PhysicalExpr;
use datafusion_physical_expr::expressions::Column;
use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
use datafusion_physical_plan::SendableRecordBatchStream;
use datafusion_physical_plan::empty::EmptyExec;
use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
use futures::{StreamExt, TryStreamExt};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

// Adjacent TRUE rows on opposite sides of logical boundaries must never form a
// pair. The NULL-key partition, an all-failed partition, and a successful pair
// after Boolean NULL also distinguish key equality from predicate validity.
const INPUT: [(Option<i32>, Option<bool>); 14] = [
    (None, Some(false)),
    (None, Some(true)),
    (None, Some(true)),
    (None, Some(true)),
    (Some(1), Some(true)),
    (Some(2), Some(true)),
    (Some(2), Some(true)),
    (Some(2), None),
    (Some(2), Some(true)),
    (Some(2), Some(true)),
    (Some(3), Some(false)),
    (Some(3), Some(false)),
    (Some(3), Some(false)),
    (Some(3), Some(false)),
];

// Compare every visible scalar, including duplicate navigation rows and match
// metadata. Canonical ordering makes the comparison independent of flush-batch
// boundaries while retaining the full output multiset.
type OutputRow = (
    Option<i32>,
    Option<i32>,
    Option<String>,
    Option<i64>,
    Option<i64>,
);

#[derive(Clone, Copy, Debug)]
enum Mode {
    Optimized,
    Packed,
    General,
    NoOptimizer,
}

fn pattern(quantifier: RepetitionQuantifier) -> Pattern {
    Pattern::Repetition(
        Box::new(Pattern::Symbol(Symbol::Named("A".to_string()))),
        quantifier,
    )
}

fn input_batch(input: &[(Option<i32>, Option<bool>)]) -> Result<RecordBatch> {
    let schema = Arc::new(Schema::new(vec![
        Field::new("p", DataType::Int32, true),
        Field::new("x", DataType::Int32, true),
        Field::new("__mr_symbol_a", DataType::Boolean, true),
    ]));
    let keys = Int32Array::from(input.iter().map(|(key, _)| *key).collect::<Vec<_>>());
    let ids = Int32Array::from((0..input.len() as i32).collect::<Vec<_>>());
    // Keep the data bit set beneath NULL: treating a raw value bit as TRUE would
    // select a different pair and alter later match numbers.
    let values = BooleanArray::new(
        BooleanBuffer::from(
            input
                .iter()
                .map(|(_, value)| value.unwrap_or(true))
                .collect::<Vec<_>>(),
        ),
        Some(NullBuffer::from(
            input
                .iter()
                .map(|(_, value)| value.is_some())
                .collect::<Vec<_>>(),
        )),
    );
    Ok(RecordBatch::try_new(
        schema,
        vec![Arc::new(keys), Arc::new(ids), Arc::new(values)],
    )?)
}

fn decode(batches: Vec<RecordBatch>) -> Vec<OutputRow> {
    let mut rows = Vec::new();
    for batch in batches {
        let keys = batch.column(0).as_primitive::<Int32Type>();
        let ids = batch.column(1).as_primitive::<Int32Type>();
        let classifiers = batch.column(2).as_string::<i32>();
        let matches = batch.column(3).as_primitive::<Int64Type>();
        let sequences = batch.column(4).as_primitive::<Int64Type>();
        for row in 0..batch.num_rows() {
            rows.push((
                keys.is_valid(row).then(|| keys.value(row)),
                ids.is_valid(row).then(|| ids.value(row)),
                classifiers
                    .is_valid(row)
                    .then(|| classifiers.value(row).to_owned()),
                matches.is_valid(row).then(|| matches.value(row)),
                sequences.is_valid(row).then(|| sequences.value(row)),
            ));
        }
    }
    rows
}

async fn run(
    pattern: Pattern,
    empty_matches: EmptyMatchesMode,
    navigation: NavigationOffsets,
    cuts: &[usize],
    threshold: usize,
    mode: Mode,
) -> Result<Vec<OutputRow>> {
    let (mut rows, _, _) = run_observation(
        &INPUT,
        pattern,
        empty_matches,
        navigation,
        cuts,
        threshold,
        mode,
    )
    .await?;
    rows.sort();
    Ok(rows)
}

async fn run_observation(
    input: &[(Option<i32>, Option<bool>)],
    pattern: Pattern,
    empty_matches: EmptyMatchesMode,
    navigation: NavigationOffsets,
    cuts: &[usize],
    threshold: usize,
    mode: Mode,
) -> Result<(
    Vec<OutputRow>,
    ExecutionPlanMetricsSet,
    crate::execution::metrics::PatternMetrics,
)> {
    let batch = input_batch(input)?;
    let mut start = 0;
    let mut batches = Vec::new();
    // Repeated cuts deliver real empty batches directly to the stream, including
    // while a candidate or output-navigation window crosses an input boundary.
    for end in cuts.iter().copied().chain([batch.num_rows()]) {
        batches.push(Ok(batch.slice(start, end - start)));
        start = end;
    }
    let input = Box::pin(RecordBatchStreamAdapter::new(
        batch.schema(),
        futures::stream::iter(batches),
    ));
    let (stream, metrics) = observed_stream(
        input,
        pattern,
        empty_matches,
        navigation,
        threshold,
        mode,
        None,
    )?;
    let observed = stream.metrics_for_test().clone();
    Ok((decode(stream.try_collect().await?), metrics, observed))
}

fn observed_stream(
    input: SendableRecordBatchStream,
    pattern: Pattern,
    empty_matches: EmptyMatchesMode,
    navigation: NavigationOffsets,
    threshold: usize,
    mode: Mode,
    execution: Option<(SliceControl, Arc<datafusion_execution::TaskContext>)>,
) -> Result<(
    MatchRecognizeStream<impl futures::Stream<Item = Result<RecordBatch>> + Send>,
    ExecutionPlanMetricsSet,
)> {
    let (slice, context) = execution.unwrap_or_default();
    let schema = input.schema();
    let key = Arc::new(Column::new("p", 0)) as Arc<dyn PhysicalExpr>;
    let mut spec = TestPlanSpec::new(Arc::new(EmptyExec::new(Arc::clone(&schema))));
    spec.pattern = pattern;
    spec.partition_by = vec![Arc::clone(&key)];
    spec.rows_per_match = RowsPerMatch::AllRows(empty_matches);
    spec.output_spec = MatchRecognizeOutputSpec::with_validated_navigation_offsets(
        vec![0, 1],
        vec![
            MatchMetadataColumn::Classifier,
            MatchMetadataColumn::MatchNumber,
            MatchMetadataColumn::MatchSequenceNumber,
        ],
        vec![],
        navigation,
    );
    let exec = build_test_exec(spec)?;
    let program = if matches!(mode, Mode::Packed) {
        // Classify the same nullable Boolean field as the unpacked control.
        let mut static_program = exec.program().as_ref().clone();
        let column = schema.index_of("__mr_symbol_a")?;
        let rule = (column, Operator::Eq, ScalarValue::Boolean(Some(true)));
        static_program.classification = Some(Arc::new(
            crate::execution::classification::MatchAwareClassification {
                demanded: Vec::new(),
                offsets_only_demanded: false,
                classifier: Arc::new(
                    StaticClassification::try_new(
                        column,
                        static_program
                            .base_variant()
                            .active_symbol_columns()
                            .columns(),
                        &[rule],
                    )
                    .unwrap(),
                ),
                predicates: vec![crate::execution::classification::ClassifiedPredicate {
                    bit: 1,
                    output: column,
                    symbols: 2,
                    ..Default::default()
                }],
                eager: 0,
                lane_column: None,
                required: 1,
            },
        ));
        Arc::new(static_program)
    } else {
        Arc::clone(exec.program())
    };
    let output_bindings = OutputPartitionBindings::try_new(
        schema.as_ref(),
        exec.program().output_plan(),
        [Arc::clone(&key)],
    )?;
    let mut config = MatchRecognizeConfig::default();
    config.diagnostics.disable_compact_paths = matches!(mode, Mode::General);
    config.diagnostics.disable_pattern_optimizer = matches!(mode, Mode::NoOptimizer);
    let metrics = ExecutionPlanMetricsSet::new();
    let stream = match_aware_stream(
        ExecutePatternInput {
            input: crate::execution::stream::MatchInput::Ordered(input),
            program,
            output_bindings,
            partition_by_sort_keys: vec![PhysicalSortExpr::new_default(key)],
            retention: PartitionRetention::ThresholdSafe,
            candidate_start_core_rows: None,
            output_batch_size: None,
            flush_threshold: threshold,
            config,
            metrics_set: metrics.clone(),
            task_context: context,
            partition: 0,
        },
        slice,
    )?;
    Ok((stream, metrics))
}

fn row(key: Option<i32>, id: Option<i32>, class: bool, number: i64) -> OutputRow {
    (
        key,
        id,
        class.then(|| "A".to_string()),
        Some(number),
        Some(1),
    )
}

#[tokio::test]
async fn empty_input_batches_count_toward_scheduling_yields() -> Result<()> {
    let batch = input_batch(&[(Some(1), Some(true))])?;
    let schema = batch.schema();
    let batches = std::iter::repeat_n(batch.slice(0, 0), 128).chain([batch]);
    let batches_read = Arc::new(AtomicUsize::new(0));
    let read = Arc::clone(&batches_read);
    let input = futures::stream::iter(batches).map(move |batch| {
        read.fetch_add(1, Ordering::Relaxed);
        Ok(batch)
    });
    let input = Box::pin(RecordBatchStreamAdapter::new(schema, input));
    let (mut stream, metrics) = observed_stream(
        input,
        pattern(RepetitionQuantifier::OneOrMore),
        EmptyMatchesMode::Omit,
        NavigationOffsets::ZERO,
        1,
        Mode::Optimized,
        None,
    )?;

    assert!(futures::poll!(stream.next()).is_pending());
    assert_eq!(batches_read.load(Ordering::Relaxed), 64);
    assert_eq!(
        decode(stream.try_collect().await?),
        vec![row(Some(1), Some(0), true, 1)]
    );
    let metrics = metrics.clone_inner();
    assert_eq!(metrics.sum_by_name("input_batches").unwrap().as_usize(), 1);
    assert_eq!(metrics.sum_by_name("input_rows").unwrap().as_usize(), 1);
    Ok(())
}

#[tokio::test]
async fn first_unmatched_batch_is_available_before_a_long_gap_is_materialized()
-> Result<()> {
    use datafusion_execution::runtime_env::RuntimeEnvBuilder;

    // The input fits in the pool; queuing an Arrow batch for each gap row does not.
    let mut rows = vec![(Some(1), Some(false)); 2048];
    rows.extend([(Some(1), Some(true)); 2]);
    let batch = input_batch(&rows)?;
    let input =
        RecordBatchStreamAdapter::new(batch.schema(), futures::stream::iter([Ok(batch)]));
    let runtime = RuntimeEnvBuilder::new()
        .with_memory_limit(512 * 1024, 1.0)
        .build_arc()?;
    let context =
        Arc::new(datafusion_execution::TaskContext::default().with_runtime(runtime));
    let pool = Arc::clone(context.memory_pool());
    let (mut stream, metrics) = observed_stream(
        Box::pin(input),
        pattern(RepetitionQuantifier::Exactly(2)),
        EmptyMatchesMode::WithUnmatched,
        NavigationOffsets::ZERO,
        1,
        Mode::Optimized,
        Some((SliceControl::default(), context)),
    )?;
    let first = stream.try_next().await?.expect("unmatched prefix");
    assert_eq!(decode(vec![first]), [(Some(1), Some(0), None, None, None)]);
    assert_eq!(
        metrics
            .clone_inner()
            .sum_by_name("matches_emitted")
            .unwrap()
            .as_usize(),
        0
    );
    drop(stream);
    assert_eq!(pool.reserved(), 0);
    Ok(())
}

#[tokio::test]
async fn closed_unmatched_partitions_drain_under_backpressure() -> Result<()> {
    use datafusion_execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryPool,
    };
    use datafusion_execution::runtime_env::RuntimeEnvBuilder;

    const BATCH: usize = 256;
    const LONG_KEY_BATCHES: usize = 16;
    const LIMIT: usize = 16 * 1024 * 1024;
    let mut rows = vec![(Some(0), Some(false)); BATCH];
    rows.extend(std::iter::repeat_n(
        (Some(1), Some(false)),
        LONG_KEY_BATCHES * BATCH + 1,
    ));
    rows.extend(std::iter::repeat_n((Some(2), Some(false)), BATCH - 1));
    rows.push((Some(3), Some(false)));
    let batch = input_batch(&rows)?;
    let input =
        RecordBatchStreamAdapter::new(batch.schema(), futures::stream::iter([Ok(batch)]));
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(LIMIT));
    let runtime = RuntimeEnvBuilder::new()
        .with_memory_pool(Arc::clone(&pool))
        .build_arc()?;
    let context =
        Arc::new(datafusion_execution::TaskContext::default().with_runtime(runtime));
    let (mut stream, _) = observed_stream(
        Box::pin(input),
        pattern(RepetitionQuantifier::Exactly(2)),
        EmptyMatchesMode::WithUnmatched,
        NavigationOffsets::ZERO,
        BATCH,
        Mode::Optimized,
        Some((SliceControl::default(), context)),
    )?;

    // The first key admits the input head and measures a full output batch.
    // Leave room for two such batches while the long closed key is drained.
    let first = stream.try_next().await?.expect("first closed key");
    assert_eq!(first.num_rows(), BATCH);
    let pressure = MemoryConsumer::new("closed partition backpressure").register(&pool);
    pressure.try_grow(LIMIT - pool.reserved() - 2 * first.get_array_memory_size())?;
    let mut actual = decode(vec![first]);
    for _ in 0..=LONG_KEY_BATCHES {
        let batch = stream.try_next().await?.expect("closed partition output");
        assert_eq!(batch.num_rows(), BATCH);
        actual.extend(decode(vec![batch]));
    }
    // The last full batch combines one row of key 1 with all of key 2.
    drop(pressure);
    actual.extend(decode(stream.try_collect().await?));
    let expected = rows
        .iter()
        .enumerate()
        .map(|(id, (key, _))| (*key, Some(id as i32), None, None, None))
        .collect::<Vec<_>>();
    assert_eq!(actual, expected);
    Ok(())
}

#[test]
fn budget_one_static_publication_resumes_and_drops_all_reservations() -> Result<()> {
    use std::num::NonZeroUsize;
    use std::task::{Context, Poll, Wake, Waker};

    #[derive(Default)]
    struct Wakes(AtomicUsize);
    impl Wake for Wakes {
        fn wake(self: Arc<Self>) {
            self.0.fetch_add(1, Ordering::Relaxed);
        }
        fn wake_by_ref(self: &Arc<Self>) {
            self.0.fetch_add(1, Ordering::Relaxed);
        }
    }

    // The first key cannot match. Two pairs on the next key must commit once
    // each, even when output preparation suspends between the encoded rows.
    let batch = input_batch(&[
        (Some(1), Some(false)),
        (Some(2), Some(true)),
        (Some(2), Some(true)),
        (Some(2), None),
        (Some(2), Some(true)),
        (Some(2), Some(true)),
    ])?;
    for (mode, cancel) in [
        (EmptyMatchesMode::Omit, false),
        (EmptyMatchesMode::Omit, true),
        (EmptyMatchesMode::WithUnmatched, false),
        (EmptyMatchesMode::WithUnmatched, true),
    ] {
        let task = Arc::new(datafusion_execution::TaskContext::default());
        let pool = Arc::clone(task.memory_pool());
        let input = RecordBatchStreamAdapter::new(
            batch.schema(),
            futures::stream::iter([Ok(batch.slice(0, 2)), Ok(batch.slice(2, 4))]),
        );
        let (mut stream, metrics) = observed_stream(
            Box::pin(input),
            pattern(RepetitionQuantifier::Exactly(2)),
            mode.clone(),
            NavigationOffsets::ZERO,
            1,
            Mode::Optimized,
            Some((SliceControl::for_test_budget(NonZeroUsize::MIN), task)),
        )?;
        let wakes = Arc::new(Wakes::default());
        let waker = Waker::from(Arc::clone(&wakes));
        let mut cx = Context::from_waker(&waker);
        let mut batches = Vec::new();
        let mut yielded = 0;
        loop {
            let before = wakes.0.load(Ordering::Relaxed);
            match stream.poll_next_unpin(&mut cx) {
                Poll::Pending => {
                    assert!(
                        wakes.0.load(Ordering::Relaxed) > before,
                        "static service lost its wake"
                    );
                    yielded += 1;
                    assert!(
                        yielded < 10_000,
                        "static service repeated work without progress"
                    );
                    let snapshot = metrics.clone_inner();
                    let committed =
                        snapshot.sum_by_name("matches_emitted").unwrap().as_usize();
                    assert_eq!(
                        committed,
                        snapshot
                            .sum_by_name("output.compact_matches")
                            .unwrap()
                            .as_usize(),
                        "both completed counters must be visible at the same yield"
                    );
                    if cancel && committed > 0 {
                        assert_eq!(committed, 1);
                        assert!(pool.reserved() > 0);
                        break;
                    }
                }
                Poll::Ready(Some(result)) => batches.push(result?),
                Poll::Ready(None) => {
                    assert!(!cancel, "expected a pending second winner");
                    break;
                }
            }
        }
        assert!(yielded > 1);
        if !cancel {
            let mut expected = [(1, 1, 1), (2, 1, 2), (4, 2, 1), (5, 2, 2)]
                .map(|(id, number, seq)| {
                    (
                        Some(2),
                        Some(id),
                        Some("A".to_string()),
                        Some(number),
                        Some(seq),
                    )
                })
                .to_vec();
            if mode == EmptyMatchesMode::WithUnmatched {
                expected.insert(0, (Some(1), Some(0), None, None, None));
                expected.insert(3, (Some(2), Some(3), None, None, None));
            }
            assert_eq!(decode(batches), expected);
            assert_eq!(
                metrics
                    .clone_inner()
                    .sum_by_name("output.compact_matches")
                    .unwrap()
                    .as_usize(),
                2
            );
        }
        drop(stream);
        assert_eq!(pool.reserved(), 0);
    }
    Ok(())
}

#[tokio::test]
async fn budget_one_yields_between_structurally_short_partitions() -> Result<()> {
    let rows: Vec<_> = (0..32).map(|key| (Some(key), Some(true))).collect();
    let batch = input_batch(&rows)?;
    let input =
        RecordBatchStreamAdapter::new(batch.schema(), futures::stream::iter([Ok(batch)]));
    let (mut stream, _) = observed_stream(
        Box::pin(input),
        pattern(RepetitionQuantifier::Exactly(2)),
        EmptyMatchesMode::Omit,
        NavigationOffsets::ZERO,
        rows.len() + 1,
        Mode::Optimized,
        Some((
            SliceControl::for_test_budget(std::num::NonZeroUsize::MIN),
            Arc::default(),
        )),
    )?;
    // Every key is too short for a pair. Count one logical preparation per
    // key even when no candidate scanner is opened or rows are published.
    let preparations = stream.metrics_for_test().partition_preparations.clone();
    let mut previous = 0;
    let item = futures::future::poll_fn(|cx| {
        let result = stream.poll_next_unpin(cx);
        let prepared = preparations.value();
        assert!(
            prepared - previous <= 1,
            "prepared {previous}..{prepared} partitions in a single budget-one poll"
        );
        previous = prepared;
        result
    })
    .await;
    assert!(item.transpose()?.is_none());
    assert_eq!(previous, rows.len());
    Ok(())
}

#[tokio::test]
async fn static_head_views_preserve_pairs_and_short_unmatched_suffixes() -> Result<()> {
    let expected = INPUT
        .iter()
        .enumerate()
        .map(|(id, (key, _))| {
            let selected = match id {
                1 | 5 => Some((1, 1)),
                2 | 6 => Some((1, 2)),
                8 => Some((2, 1)),
                9 => Some((2, 2)),
                _ => None,
            };
            (
                *key,
                Some(id as i32),
                selected.map(|_| "A".to_string()),
                selected.map(|(number, _)| number),
                selected.map(|(_, sequence)| sequence),
            )
        })
        .collect::<Vec<_>>();
    let empty_cuts = (0..=INPUT.len())
        .flat_map(|row| [row, row])
        .collect::<Vec<_>>();
    for (mode, threshold, cuts) in [
        (Mode::Optimized, 1024, &[][..]),
        (Mode::General, 1024, &[][..]),
        (Mode::NoOptimizer, 1024, &[][..]),
        (Mode::Optimized, 1, &[2, 6][..]),
        (Mode::General, 1024, &[4, 5, 10][..]),
        (Mode::Optimized, 1, empty_cuts.as_slice()),
        (Mode::Packed, 1, empty_cuts.as_slice()),
    ] {
        let (actual, _, observed) = run_observation(
            &INPUT,
            pattern(RepetitionQuantifier::Exactly(2)),
            EmptyMatchesMode::WithUnmatched,
            NavigationOffsets::ZERO,
            cuts,
            threshold,
            mode,
        )
        .await?;
        if cuts.is_empty() {
            // This proves false candidates do not start scans. It deliberately
            // does not claim to distinguish a Never variant from a start guard.
            assert_eq!(
                observed.candidate_starts.value(),
                3,
                "{mode:?}:false tail must not create dead scanners"
            );
        }
        assert_eq!(
            actual, expected,
            "{mode:?},threshold={threshold},cuts={cuts:?}"
        );
    }
    Ok(())
}

#[tokio::test]
async fn static_head_views_preserve_nullable_matches_and_partition_end_rows() -> Result<()>
{
    let expected = vec![
        row(None, Some(0), false, 1),
        row(None, Some(1), true, 2),
        row(None, Some(2), true, 3),
        row(None, Some(3), true, 4),
        row(None, None, false, 5),
        row(Some(1), Some(4), true, 1),
        row(Some(1), None, false, 2),
        row(Some(2), Some(5), true, 1),
        row(Some(2), Some(6), true, 2),
        row(Some(2), Some(7), false, 3),
        row(Some(2), Some(8), true, 4),
        row(Some(2), Some(9), true, 5),
        row(Some(2), None, false, 6),
        row(Some(3), Some(10), false, 1),
        row(Some(3), Some(11), false, 2),
        row(Some(3), Some(12), false, 3),
        row(Some(3), Some(13), false, 4),
        row(Some(3), None, false, 5),
    ];
    let empty_cuts = (0..=INPUT.len())
        .flat_map(|row| [row, row])
        .collect::<Vec<_>>();
    for (mode, threshold, cuts) in [
        (Mode::Optimized, 1, &[2][..]),
        (Mode::General, 1024, &[4, 5, 10][..]),
        (Mode::NoOptimizer, 1024, &[][..]),
        (Mode::Optimized, 1024, &[INPUT.len()][..]),
        (Mode::Packed, 1024, &[4, 5, 10][..]),
        (Mode::Packed, 1, empty_cuts.as_slice()),
        (Mode::Optimized, 1, empty_cuts.as_slice()),
    ] {
        let (actual, metrics, _) = run_observation(
            &INPUT,
            pattern(RepetitionQuantifier::AtMostOne),
            EmptyMatchesMode::Show,
            NavigationOffsets::ZERO,
            cuts,
            threshold,
            mode,
        )
        .await?;
        assert_eq!(
            actual, expected,
            "{mode:?},threshold={threshold},cuts={cuts:?}"
        );
        let compact = metrics
            .clone_inner()
            .sum_by_name("output.compact_matches")
            .unwrap()
            .as_usize();
        let empties = expected.iter().filter(|row| row.2.is_none()).count();
        if threshold == 1 {
            assert!(
                compact <= expected.len() - empties,
                "empty winners at a flush boundary use the resumable path"
            );
        } else if matches!(mode, Mode::Packed) {
            assert!(compact >= empties, "physical and virtual empty winners");
        }
    }
    Ok(())
}

#[tokio::test]
async fn cancelled_empty_winners_release_unflushed_output() -> Result<()> {
    let batch = input_batch(&[(Some(1), Some(false)); 16])?;
    let task = Arc::new(datafusion_execution::TaskContext::default());
    let pool = Arc::clone(task.memory_pool());
    let input =
        RecordBatchStreamAdapter::new(batch.schema(), futures::stream::iter([Ok(batch)]));
    let (mut stream, metrics) = observed_stream(
        Box::pin(input),
        pattern(RepetitionQuantifier::ZeroOrMore),
        EmptyMatchesMode::Show,
        NavigationOffsets::ZERO,
        64,
        Mode::Packed,
        Some((
            SliceControl::for_test_budget(std::num::NonZeroUsize::MIN),
            task,
        )),
    )?;
    for _ in 0..1024 {
        assert!(futures::poll!(stream.next()).is_pending());
        let compact = metrics
            .clone_inner()
            .sum_by_name("output.compact_matches")
            .unwrap()
            .as_usize();
        if compact > 0 {
            assert_eq!(
                compact, 1,
                "a one-unit poll must yield between empty winners"
            );
            assert!(pool.reserved() > 0);
            drop(stream);
            assert_eq!(pool.reserved(), 0);
            return Ok(());
        }
    }
    panic!("empty winner never committed before the output flush");
}

#[tokio::test]
async fn static_head_views_keep_navigation_inside_the_real_partition() -> Result<()> {
    let navigation = NavigationOffsets::try_from_raw(1, 1).unwrap();
    let a = Some("A".to_string());
    let expected = vec![
        (None, Some(0), None, Some(1), Some(-1)),
        (None, Some(1), a.clone(), Some(1), Some(1)),
        (None, Some(2), a.clone(), Some(1), Some(2)),
        (None, Some(3), None, Some(1), Some(i64::MAX - 1)),
        (Some(2), Some(5), a.clone(), Some(1), Some(1)),
        (Some(2), Some(6), a.clone(), Some(1), Some(2)),
        (Some(2), Some(7), None, Some(1), Some(i64::MAX - 1)),
        (Some(2), Some(7), None, Some(2), Some(-1)),
        (Some(2), Some(8), a.clone(), Some(2), Some(1)),
        (Some(2), Some(9), a, Some(2), Some(2)),
    ];
    let (ordered, _, _) = run_observation(
        &INPUT,
        pattern(RepetitionQuantifier::Exactly(2)),
        EmptyMatchesMode::Omit,
        navigation,
        &[],
        1024,
        Mode::General,
    )
    .await?;
    assert_eq!(
        ordered, expected,
        "PREV/selected/NEXT rows retain encoding order within the true key boundary"
    );
    let mut expected = expected;
    expected.sort();
    let all_rows = (1..INPUT.len()).collect::<Vec<_>>();
    let empty_cuts = (0..=INPUT.len())
        .flat_map(|row| [row, row])
        .collect::<Vec<_>>();
    for (mode, threshold, cuts) in [
        (Mode::Optimized, 1, &[2, 6, 9][..]),
        (Mode::General, 1024, &[4, 5][..]),
        (Mode::NoOptimizer, 1, all_rows.as_slice()),
        (Mode::Optimized, 1, empty_cuts.as_slice()),
    ] {
        let actual = run(
            pattern(RepetitionQuantifier::Exactly(2)),
            EmptyMatchesMode::Omit,
            navigation,
            cuts,
            threshold,
            mode,
        )
        .await?;
        assert_eq!(
            actual, expected,
            "{mode:?},threshold={threshold},cuts={cuts:?}"
        );
    }
    Ok(())
}

#[tokio::test]
async fn static_history_replay_reuses_open_runs_across_input_heads() -> Result<()> {
    for run_rows in [8, 64] {
        let mut input = vec![(Some(1), Some(true)); 2 * run_rows + 1];
        input[run_rows].1 = Some(false);
        let cuts = (1..input.len()).collect::<Vec<_>>();
        let (actual, metrics, preparations) = run_observation(
            &input,
            pattern(RepetitionQuantifier::OneOrMore),
            EmptyMatchesMode::Omit,
            NavigationOffsets::ZERO,
            &cuts,
            1,
            Mode::General,
        )
        .await?;
        let expected = [0, run_rows + 1]
            .into_iter()
            .enumerate()
            .flat_map(|(run, start)| {
                (0..run_rows).map(move |row| {
                    (
                        Some(1),
                        Some((start + row) as i32),
                        Some("A".to_string()),
                        Some(run as i64 + 1),
                        Some(row as i64 + 1),
                    )
                })
            })
            .collect::<Vec<_>>();
        assert_eq!(actual, expected);
        let metrics = metrics.clone_inner();
        let count = |name| metrics.sum_by_name(name).unwrap().as_usize();
        assert_eq!(count("input_batches"), input.len());
        // The unified scan retains one logical scratch across all heads and
        // resumes each greedy run instead of opening a candidate per replay.
        assert_eq!(
            preparations.partition_preparations.value(),
            1,
            "run_rows={run_rows}"
        );
        assert_eq!(
            preparations.candidate_starts.value(),
            2,
            "run_rows={run_rows}"
        );
    }
    Ok(())
}

#[tokio::test]
async fn mandatory_start_anchor_drains_open_heads_without_losing_output() -> Result<()> {
    let unmatched = INPUT
        .iter()
        .enumerate()
        .map(|(id, (key, _))| {
            let selected = matches!(id, 4..=6);
            (
                *key,
                Some(id as i32),
                selected.then(|| "A".to_string()),
                selected.then_some(1),
                selected.then_some(if id == 6 { 2 } else { 1 }),
            )
        })
        .collect::<Vec<_>>();
    let nullable = vec![
        row(None, Some(0), false, 1),
        row(Some(1), Some(4), true, 1),
        row(Some(2), Some(5), true, 1),
        (Some(2), Some(6), Some("A".to_string()), Some(1), Some(2)),
        row(Some(3), Some(10), false, 1),
    ];
    // Include empty input batches and an empty final head. Failed-first and
    // successful-first partitions must drain later heads without fresh starts.
    let cuts = (0..=INPUT.len())
        .flat_map(|row| [row, row])
        .collect::<Vec<_>>();
    for (quantifier, output, mut expected) in [
        (
            RepetitionQuantifier::OneOrMore,
            EmptyMatchesMode::WithUnmatched,
            unmatched,
        ),
        (
            RepetitionQuantifier::ZeroOrMore,
            EmptyMatchesMode::Show,
            nullable,
        ),
    ] {
        expected.sort();
        for (mode, threshold, cuts) in [
            (Mode::Optimized, 1024, &[][..]),
            (Mode::Optimized, 1, cuts.as_slice()),
            (Mode::NoOptimizer, 1, cuts.as_slice()),
        ] {
            let (mut actual, metrics, observed) = run_observation(
                &INPUT,
                Pattern::Concat(vec![
                    Pattern::Symbol(Symbol::Start),
                    pattern(quantifier.clone()),
                ]),
                output.clone(),
                NavigationOffsets::ZERO,
                cuts,
                threshold,
                mode,
            )
            .await?;
            actual.sort();
            assert_eq!(actual, expected, "{quantifier:?}, {mode:?}, cuts={cuts:?}");
            if matches!(mode, Mode::NoOptimizer) {
                let expected_starts =
                    if matches!(quantifier, RepetitionQuantifier::OneOrMore) {
                        2 // First-row admission rejects two failed partitions.
                    } else {
                        4 // Nullable programs still attempt every partition start.
                    };
                assert_eq!(
                    observed.candidate_starts.value(),
                    expected_starts,
                    "only admitted logical partition starts enter the scanner",
                );
                // Non-nullable `^ A+` uses boundary-anchored Lane;
                // nullable `^ A*` uses General. Both retain logical scratch.
                let expected_metric =
                    if matches!(quantifier, RepetitionQuantifier::OneOrMore) {
                        "route.scan.specialized"
                    } else {
                        "route.scan.generic"
                    };
                let scan_admissions = metrics
                    .clone_inner()
                    .iter()
                    .filter(|metric| metric.value().name() == expected_metric)
                    .map(|metric| metric.value().as_usize())
                    .sum::<usize>();
                if cuts.is_empty() {
                    assert_eq!(
                        scan_admissions, expected_starts,
                        "unified route counters record admitted candidates ({expected_metric})",
                    );
                } else {
                    assert!(
                        (1..=expected_starts).contains(&scan_admissions),
                        "retiring heads may release idle_scan before reopening ({expected_metric}): {scan_admissions}",
                    );
                }
            }
        }
    }
    Ok(())
}

#[tokio::test]
async fn end_guard_preserves_later_starts_unmatched_rows_and_nullable_end_matches()
-> Result<()> {
    let selected = |id| match id {
        1..=3 => Some(id as i64),
        4 | 8 => Some(1),
        9 => Some(2),
        _ => None,
    };
    let unmatched = INPUT
        .iter()
        .enumerate()
        .map(|(id, (key, _))| {
            (
                *key,
                Some(id as i32),
                selected(id).map(|_| "A".to_string()),
                selected(id).map(|_| 1),
                selected(id),
            )
        })
        .collect::<Vec<_>>();
    let mut nullable = INPUT
        .iter()
        .enumerate()
        .filter_map(|(id, (key, _))| {
            selected(id).map(|seq| {
                (
                    *key,
                    Some(id as i32),
                    Some("A".to_string()),
                    Some(1),
                    Some(seq),
                )
            })
        })
        .collect::<Vec<_>>();
    for key in [None, Some(1), Some(2), Some(3)] {
        nullable.push(row(key, None, false, if key == Some(3) { 1 } else { 2 }));
    }
    let cuts = (0..=INPUT.len())
        .flat_map(|row| [row, row])
        .collect::<Vec<_>>();
    for (quantifier, output, mut expected) in [
        (
            RepetitionQuantifier::OneOrMore,
            EmptyMatchesMode::WithUnmatched,
            unmatched,
        ),
        (
            RepetitionQuantifier::ZeroOrMore,
            EmptyMatchesMode::Show,
            nullable,
        ),
    ] {
        expected.sort();
        for (mode, threshold, cuts) in [
            (Mode::NoOptimizer, 1024, &[][..]),
            (Mode::Optimized, 1, cuts.as_slice()),
            (Mode::NoOptimizer, 1, cuts.as_slice()),
        ] {
            let (mut actual, metrics, observed) = run_observation(
                &INPUT,
                Pattern::Concat(vec![
                    pattern(quantifier.clone()),
                    Pattern::Symbol(Symbol::End),
                ]),
                output.clone(),
                NavigationOffsets::ZERO,
                cuts,
                threshold,
                mode,
            )
            .await?;
            actual.sort();
            assert_eq!(actual, expected, "{quantifier:?}, {mode:?}, cuts={cuts:?}");
            if cuts.is_empty() && matches!(quantifier, RepetitionQuantifier::OneOrMore) {
                assert_eq!(
                    observed.candidate_starts.value(),
                    3,
                    "the end guard and trailing suffix skip impossible starts"
                );
                assert_eq!(
                    metrics
                        .clone_inner()
                        .iter()
                        .filter(|metric| metric.value().name() == "route.scan.generic")
                        .map(|metric| metric.value().as_usize())
                        .sum::<usize>(),
                    3,
                    "each admitted candidate uses the unified General route"
                );
            }
        }
    }
    Ok(())
}