datafusion-match-recognize 0.55.0

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
// 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.

//! DataFusion stream lifecycle for the unified matcher.

use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

use crate::compat::memory::RecordBatchMemoryCounter;
use crate::execution::matching::PartitionKey;
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::Result;
use datafusion::execution::RecordBatchStream;
use datafusion::execution::memory_pool::MemoryReservation;
use datafusion::physical_plan::SendableRecordBatchStream;
use datafusion::physical_plan::coop::cooperative;
use datafusion::physical_plan::metrics::Time;
use datafusion_hash_grouped_order::{
    GroupedBatch, PartitionRange, SendableGroupedBatchStream,
};
use futures::stream::try_unfold;
use futures::stream::{FusedStream, Stream};

use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::common::scheduling::{SliceControl, with_active_slice};
use crate::execution::metrics::PatternMetrics;
use crate::execution::storage::history_buffer::SharedHistoryBuffer;

pub(crate) mod ordered_input;
pub(crate) use ordered_input::{PhysicalInput, SelectedHead};
pub(crate) mod output_coalescing;
use output_coalescing::OutputCoalescer;
pub(crate) mod stateful_stream;
use stateful_stream::AwareEngine;

/// Empty batches count toward the input fairness limit as well.
pub(crate) const READY_INPUT_BATCHES_PER_YIELD: usize = 64;

/// The physical planner verifies the grouped child's partition contract before
/// opening its metadata-preserving stream.
pub(crate) enum MatchInput {
    Ordered(SendableRecordBatchStream),
    Grouped(SendableGroupedBatchStream),
}

impl MatchInput {
    pub(crate) fn schema(&self) -> SchemaRef {
        match self {
            Self::Ordered(stream) => stream.schema(),
            Self::Grouped(stream) => stream.schema(),
        }
    }
}

pub(super) enum InputBatch {
    Ordered(RecordBatch, Option<Arc<MemoryReservation>>),
    Grouped(
        GroupedBatch,
        Option<Arc<MemoryReservation>>,
        Option<MemoryReservation>,
    ),
}

struct PendingChunk {
    input: InputBatch,
    offset: usize,
    range_index: usize,
    // The original column handles and range vector remain live across polls,
    // independently of admitted fragments. Release them with the final fragment.
    pending_memory: MemoryReservation,
}

/// Upstream polling is timed independently so the matcher charges only its
/// own active work to DataFusion's elapsed_compute metric.
struct UpstreamInput {
    stream: Option<MatchInput>,
    poll_time: Time,
    batch_size: usize,
    pending: Option<PendingChunk>,
}

impl UpstreamInput {
    fn new(stream: MatchInput, batch_size: usize) -> Self {
        Self {
            stream: Some(stream),
            poll_time: Time::new(),
            batch_size: batch_size.max(1),
            pending: None,
        }
    }

    /// Slice before classification or storage admission. Group completion belongs
    /// only to the fragment containing the original range end; subsequent chunks
    /// therefore retain the same open-group origin in `PhysicalInput::admit`.
    fn next_chunk(&mut self) -> Result<InputBatch> {
        let PendingChunk {
            input,
            offset,
            mut range_index,
            pending_memory,
        } = self.pending.take().expect("pending input");
        let batch = match &input {
            InputBatch::Ordered(batch, _) => batch,
            InputBatch::Grouped(grouped, _, _) => &grouped.batch,
        };
        let end = offset + (batch.num_rows() - offset).min(self.batch_size);
        let chunk = batch.slice(offset, end - offset);
        let result = match &input {
            InputBatch::Ordered(_, backing) => {
                InputBatch::Ordered(chunk, backing.clone())
            }
            InputBatch::Grouped(grouped, backing, _) => {
                // Charge each capacity increase before allocation, and carry the
                // lease through classification into GroupedRanges admission.
                let chunk_range_memory = pending_memory.new_empty();
                let mut partition_ranges = Vec::new();
                let mut cursor = offset;
                while cursor < end {
                    let range = grouped.partition_ranges.get(range_index).ok_or_else(||
                        datafusion::common::internal_datafusion_err!("MATCH_RECOGNIZE grouped ranges do not cover their input batch"))?;
                    let expected_start = if range_index == 0 {
                        0
                    } else {
                        grouped.partition_ranges[range_index - 1].end
                    };
                    if range.start != expected_start
                        || range.end <= cursor
                        || range.end > batch.num_rows()
                    {
                        return datafusion::common::internal_err!(
                            "MATCH_RECOGNIZE invalid grouped partition coverage"
                        );
                    }
                    let stop = range.end.min(end);
                    crate::execution::common::memory::try_reserve_accounted(
                        &mut partition_ranges,
                        &chunk_range_memory,
                        1,
                        "chunk partition ranges",
                    )?;
                    partition_ranges.push(PartitionRange {
                        start: cursor - offset,
                        end: stop - offset,
                        is_complete: stop == range.end && range.is_complete,
                    });
                    cursor = stop;
                    if stop == range.end {
                        range_index += 1;
                    }
                }
                if end == batch.num_rows()
                    && range_index != grouped.partition_ranges.len()
                {
                    return datafusion::common::internal_err!(
                        "MATCH_RECOGNIZE invalid grouped partition coverage"
                    );
                }
                InputBatch::Grouped(
                    GroupedBatch {
                        batch: chunk,
                        partition_ranges,
                    },
                    backing.clone(),
                    Some(chunk_range_memory),
                )
            }
        };
        if end < batch.num_rows() {
            self.pending = Some(PendingChunk {
                input,
                offset: end,
                range_index,
                pending_memory,
            });
        }
        Ok(result)
    }

    fn stage_chunks(
        &mut self,
        mut input: InputBatch,
        memory: &MemoryReservation,
    ) -> Result<()> {
        let (batch, backing, range_bytes) = match &mut input {
            InputBatch::Ordered(batch, backing) => (batch, backing, 0),
            InputBatch::Grouped(grouped, backing, _) => (
                &mut grouped.batch,
                backing,
                grouped
                    .partition_ranges
                    .capacity()
                    .checked_mul(size_of::<PartitionRange>())
                    .ok_or_else(crate::execution::matching::key_memory_overflow)?,
            ),
        };
        let shared = memory.new_empty();
        shared.try_grow(
            RecordBatchMemoryCounter::new().count_batch_with_array_overhead(batch),
        )?;
        let pending_memory = memory.new_empty();
        let handle_bytes = batch
            .num_columns()
            .checked_mul(size_of::<datafusion::arrow::array::ArrayRef>())
            .and_then(|bytes| bytes.checked_add(range_bytes))
            .ok_or_else(crate::execution::matching::key_memory_overflow)?;
        pending_memory.try_grow(handle_bytes)?;
        *backing = Some(Arc::new(shared));
        self.pending = Some(PendingChunk {
            input,
            offset: 0,
            range_index: 0,
            pending_memory,
        });
        Ok(())
    }

    fn poll_batch(
        &mut self,
        cx: &mut Context<'_>,
        memory: Option<&MemoryReservation>,
    ) -> Poll<Result<Option<InputBatch>>> {
        if self.pending.is_some() {
            return Poll::Ready(self.next_chunk().map(Some));
        }
        let stream = self.stream.as_mut().ok_or_else(|| {
            datafusion::common::internal_datafusion_err!(
                "MATCH_RECOGNIZE requested input after end of stream"
            )
        })?;
        let result = {
            let _timer = self.poll_time.timer();
            match stream {
                MatchInput::Ordered(stream) => {
                    stream.as_mut().poll_next(cx).map(|item| {
                        item.map(|batch| batch.map(|b| InputBatch::Ordered(b, None)))
                            .transpose()
                    })
                }
                MatchInput::Grouped(stream) => {
                    stream.as_mut().poll_next(cx).map(|item| {
                        item.map(|batch| {
                            batch.map(|b| InputBatch::Grouped(b, None, None))
                        })
                        .transpose()
                    })
                }
            }
        };
        if let Poll::Ready(Ok(Some(input))) = result {
            let rows = match &input {
                InputBatch::Ordered(batch, _) => batch.num_rows(),
                InputBatch::Grouped(grouped, _, _) => grouped.batch.num_rows(),
            };
            if rows > self.batch_size {
                self.stage_chunks(
                    input,
                    memory.expect("chunking requires history memory"),
                )?;
                return Poll::Ready(self.next_chunk().map(Some));
            }
            return Poll::Ready(Ok(Some(input)));
        }
        if matches!(result, Poll::Ready(Ok(None))) {
            self.stream = None;
        }
        result
    }
}

pub(crate) enum EngineStep {
    Select(Option<PartitionKey>),
    NeedInput,
    Emit(RecordBatch),
    Done,
}

struct PartitionStream {
    engine: AwareEngine,
    upstream: UpstreamInput,
    coalescer: Option<OutputCoalescer>,
    resume: Option<EngineStep>,
    metrics: PatternMetrics,
}

impl PartitionStream {
    async fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
        loop {
            if let Some(batch) = self
                .coalescer
                .as_mut()
                .and_then(OutputCoalescer::next_completed_batch)
            {
                return Ok(Some(batch));
            }
            let action = match self.resume.take() {
                Some(step) => step,
                None => self.engine.advance().await?,
            };
            match action {
                EngineStep::Select(ref key) => {
                    if let Poll::Ready(head) =
                        self.engine.input.select(key.as_ref()).await?
                    {
                        self.engine.install_head(head).await?;
                        self.engine.input.slice.yield_if_expired().await;
                        continue;
                    }
                    // Keep the open key across both output publication and upstream Pending.
                    self.resume = Some(action);
                }
                EngineStep::NeedInput => {}
                EngineStep::Emit(batch) => {
                    let Some(coalescer) = &mut self.coalescer else {
                        return Ok(Some(batch));
                    };
                    coalescer.push_batch(batch)?;
                    if let Some(batch) = coalescer.next_completed_batch() {
                        return Ok(Some(batch));
                    }
                    self.engine.input.slice.yield_if_expired().await;
                    continue;
                }
                EngineStep::Done => {
                    if let Some(batch) = self
                        .coalescer
                        .as_mut()
                        .map(OutputCoalescer::flush_tail)
                        .transpose()?
                        .flatten()
                    {
                        self.resume = Some(action);
                        return Ok(Some(batch));
                    }
                    return Ok(None);
                }
            }
            if let Some(batch) = self
                .coalescer
                .as_mut()
                .map(OutputCoalescer::flush_tail)
                .transpose()?
                .flatten()
            {
                // The head selection resumes by polling input. Explicit navigation
                // lookahead needs its request retained as well.
                self.resume.get_or_insert(EngineStep::NeedInput);
                return Ok(Some(batch));
            }
            let batch = futures::future::poll_fn(|cx| {
                self.upstream
                    .poll_batch(cx, Some(self.engine.input.ordered.history.memory()))
            })
            .await?;
            self.engine.input.admit(batch, &self.metrics).await?;
            self.engine.input.slice.yield_if_expired().await;
        }
    }
}

pub(crate) struct MatchRecognizeStream<S> {
    driver: Option<Pin<Box<S>>>,
    upstream_time: Time,
    slice: SliceControl,
    schema: SchemaRef,
    metrics: PatternMetrics,
}

pub(super) fn matcher_stream(
    engine: AwareEngine,
    coalescer: Option<OutputCoalescer>,
    slice: SliceControl,
    schema: SchemaRef,
    metrics: PatternMetrics,
    input: MatchInput,
    batch_size: usize,
) -> MatchRecognizeStream<impl Stream<Item = Result<RecordBatch>> + Send> {
    let upstream = UpstreamInput::new(input, batch_size);
    let upstream_time = upstream.poll_time.clone();
    let state = Box::new(PartitionStream {
        engine,
        upstream,
        coalescer,
        resume: None,
        metrics: metrics.clone(),
    });
    // Pin the stream once. The future holds direct borrows of the engine and
    // selected head across yields, without a per-partition or per-match allocation.
    let driver = try_unfold(Some(state), |state| async move {
        let Some(mut state) = state else {
            return Ok(None);
        };
        let batch = state.next_batch().await?;
        Ok(batch.map(|batch| {
            // Release the scan and retained input before handing out the last
            // coalesced batch, even if the consumer never polls again.
            let finished = matches!(state.resume, Some(EngineStep::Done))
                && state
                    .coalescer
                    .as_ref()
                    .is_none_or(OutputCoalescer::is_empty);
            (batch, (!finished).then_some(state))
        }))
    });
    MatchRecognizeStream {
        driver: Some(Box::pin(driver)),
        upstream_time,
        slice,
        schema,
        metrics,
    }
}

/// Drain an upstream stream for a statically impossible (`NormalizedPattern::Never`)
/// program that emits zero rows and evaluates no matcher-side fallible predicates.
/// Preserves upstream I/O, SQL errors, schema/group checks, deadline/cancellation
/// checks, slice-aware cooperative yielding, and input metrics without buffering
/// history or evaluating static classifications.
pub(crate) fn drain_empty_stream(
    input: MatchInput,
    expected_input_schema: SchemaRef,
    output_schema: SchemaRef,
    metrics: PatternMetrics,
    slice: SliceControl,
    governor: crate::execution::common::work::WorkGovernor,
) -> MatchRecognizeStream<impl Stream<Item = Result<RecordBatch>> + Send> {
    let upstream = UpstreamInput::new(input, usize::MAX);
    let upstream_time = upstream.poll_time.clone();
    let driver_metrics = metrics.clone();
    let yield_slice = slice.clone();
    let driver = try_unfold(Some((upstream, governor)), move |state| {
        let expected_input_schema = Arc::clone(&expected_input_schema);
        let metrics = driver_metrics.clone();
        let yield_slice = yield_slice.clone();
        async move {
            let Some((mut upstream, mut governor)) = state else {
                return Ok(None);
            };
            let mut ready = 0usize;
            let mut open_group = false;
            while let Some(batch) =
                futures::future::poll_fn(|cx| upstream.poll_batch(cx, None)).await?
            {
                let (batch, ranges) = match batch {
                    InputBatch::Ordered(b, _) => (b, None),
                    InputBatch::Grouped(
                        GroupedBatch {
                            batch,
                            partition_ranges,
                        },
                        _,
                        _,
                    ) => (batch, Some(partition_ranges)),
                };
                let rows = batch.num_rows();
                let mut charged_rows = 0usize;
                if rows == 0 && ranges.as_ref().is_some_and(|r| !r.is_empty()) {
                    return datafusion::common::internal_err!(
                        "MATCH_RECOGNIZE empty grouped batch contains partition ranges"
                    );
                }
                if rows != 0 {
                    SharedHistoryBuffer::validate_batch_schema(
                        &expected_input_schema,
                        batch.schema_ref(),
                    )?;
                    if let Some(ranges) = ranges {
                        let mut cursor = 0usize;
                        for (idx, range) in ranges.iter().enumerate() {
                            if range.start != cursor
                                || range.end <= range.start
                                || range.end > rows
                            {
                                return datafusion::common::internal_err!(
                                    "MATCH_RECOGNIZE grouped batch partition ranges do not cover 0..{rows}"
                                );
                            }
                            if !range.is_complete && idx + 1 != ranges.len() {
                                return datafusion::common::internal_err!(
                                    "MATCH_RECOGNIZE incomplete grouped partition is not the final range"
                                );
                            }
                            cursor = range.end;
                            if (idx + 1).is_multiple_of(COARSE_WORK_BATCH_SIZE)
                                || idx + 1 == ranges.len()
                            {
                                // Range validation is work even for an impossible
                                // pattern. Keep this cursor in the async frame so
                                // large grouped batches can yield before their tail.
                                // Charge covered rows here, not again at batch end.
                                governor
                                    .record_completed(cursor - charged_rows, || false)?;
                                charged_rows = cursor;
                                if governor
                                    .take_yield_if_due(yield_slice.current_policy())
                                {
                                    ready = 0;
                                    yield_slice.yield_once().await;
                                }
                            }
                        }
                        if cursor != rows {
                            return datafusion::common::internal_err!(
                                "MATCH_RECOGNIZE grouped batch partition ranges do not cover 0..{rows}"
                            );
                        }
                        open_group = ranges.last().is_some_and(|r| !r.is_complete);
                    }
                    metrics.input_batches.add(1);
                    metrics.input_rows.add(rows);
                }
                drop(batch);
                governor.record_completed(rows.max(1) - charged_rows, || false)?;
                ready += 1;
                let policy = yield_slice.current_policy();
                if ready >= READY_INPUT_BATCHES_PER_YIELD
                    || governor.take_yield_if_due(policy)
                {
                    ready = 0;
                    yield_slice.yield_once().await;
                }
            }
            if open_group {
                return datafusion::common::internal_err!(
                    "MATCH_RECOGNIZE grouped input ended inside an incomplete partition"
                );
            }
            Ok(None)
        }
    });
    MatchRecognizeStream {
        driver: Some(Box::pin(driver)),
        upstream_time,
        slice,
        schema: output_schema,
        metrics,
    }
}

impl<S: Stream<Item = Result<RecordBatch>> + Send> MatchRecognizeStream<S> {
    #[cfg(test)]
    pub(crate) fn metrics_for_test(&self) -> &PatternMetrics {
        &self.metrics
    }

    pub(crate) fn scheduled(self, duration: Option<Duration>) -> SendableRecordBatchStream
    where
        S: 'static,
    {
        let control = self.slice.clone();
        Box::pin(with_active_slice(cooperative(self), control, duration))
    }
}

impl<S: Stream<Item = Result<RecordBatch>> + Send> Stream for MatchRecognizeStream<S> {
    type Item = Result<RecordBatch>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        let Some(driver) = &mut this.driver else {
            return Poll::Ready(None);
        };
        let before = this.upstream_time.value();
        let start = Instant::now();
        let result = driver.as_mut().poll_next(cx);
        if matches!(result, Poll::Ready(None | Some(Err(_)))) {
            this.driver = None;
        }
        let baseline = &this.metrics.baseline_metrics;
        let result = baseline.record_poll(result);
        let elapsed = start.elapsed();
        let upstream = Duration::from_nanos(
            this.upstream_time.value().saturating_sub(before) as u64,
        );
        baseline
            .elapsed_compute()
            .add_duration(elapsed.saturating_sub(upstream));
        this.metrics.record_poll_time(elapsed);
        result
    }
}

impl<S: Stream<Item = Result<RecordBatch>> + Send> FusedStream
    for MatchRecognizeStream<S>
{
    fn is_terminated(&self) -> bool {
        self.driver.is_none()
    }
}

impl<S: Stream<Item = Result<RecordBatch>> + Send> RecordBatchStream
    for MatchRecognizeStream<S>
{
    fn schema(&self) -> SchemaRef {
        Arc::clone(&self.schema)
    }
}

#[cfg(test)]
mod input_chunk_tests;

#[cfg(test)]
mod drain_tests {
    use super::*;
    use crate::execution::common::work::WorkGovernor;
    use datafusion::arrow::array::Int64Array;
    use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
    use datafusion_hash_grouped_order::GroupedBatchStream;
    use std::num::NonZeroUsize;

    struct GroupedInput {
        schema: SchemaRef,
        batches: std::vec::IntoIter<GroupedBatch>,
    }

    impl Stream for GroupedInput {
        type Item = Result<GroupedBatch>;

        fn poll_next(
            mut self: Pin<&mut Self>,
            _: &mut Context<'_>,
        ) -> Poll<Option<Self::Item>> {
            Poll::Ready(self.batches.next().map(Ok))
        }
    }

    impl GroupedBatchStream for GroupedInput {
        fn schema(&self) -> SchemaRef {
            Arc::clone(&self.schema)
        }
    }

    fn singleton_batch(rows: usize) -> Result<GroupedBatch> {
        Ok(GroupedBatch {
            batch: RecordBatch::try_from_iter([(
                "id",
                Arc::new(Int64Array::from_iter_values(0..rows as i64))
                    as datafusion::arrow::array::ArrayRef,
            )])?,
            partition_ranges: (0..rows)
                .map(|start| PartitionRange {
                    start,
                    end: start + 1,
                    is_complete: true,
                })
                .collect(),
        })
    }

    fn drain(
        batches: Vec<GroupedBatch>,
        budget: NonZeroUsize,
    ) -> MatchRecognizeStream<impl Stream<Item = Result<RecordBatch>> + Send> {
        let schema = batches[0].batch.schema();
        drain_empty_stream(
            MatchInput::Grouped(Box::pin(GroupedInput {
                schema: Arc::clone(&schema),
                batches: batches.into_iter(),
            })),
            Arc::clone(&schema),
            schema,
            PatternMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
            SliceControl::for_test_budget(budget),
            WorkGovernor::default(),
        )
    }

    #[test]
    fn grouped_drain_yields_before_malformed_trailing_range() -> Result<()> {
        let rows = 4096 + 17;
        let mut batch = singleton_batch(rows)?;
        batch.partition_ranges.last_mut().unwrap().end = rows + 1;
        let mut stream = drain(vec![batch], NonZeroUsize::MIN);
        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
        assert!(Pin::new(&mut stream).poll_next(&mut cx).is_pending());
        // Validation has not reached the malformed tail or committed batch metrics.
        assert_eq!(stream.metrics_for_test().input_batches.value(), 0);
        assert_eq!(stream.metrics_for_test().input_rows.value(), 0);
        let mut pending = 1;
        loop {
            match Pin::new(&mut stream).poll_next(&mut cx) {
                Poll::Pending => {
                    pending += 1;
                    assert!(pending <= rows.div_ceil(COARSE_WORK_BATCH_SIZE));
                }
                Poll::Ready(Some(Err(error))) => {
                    assert!(
                        error.to_string().contains("partition ranges do not cover"),
                        "{error}"
                    );
                    break;
                }
                other => panic!("expected trailing validation error, got {other:?}"),
            }
        }
        assert_eq!(pending, rows / COARSE_WORK_BATCH_SIZE);
        assert_eq!(stream.metrics_for_test().input_batches.value(), 0);
        assert_eq!(stream.metrics_for_test().input_rows.value(), 0);
        assert!(stream.is_terminated());
        Ok(())
    }

    #[test]
    fn grouped_drain_yields_and_charges_each_row_once() -> Result<()> {
        let rows: usize = 4096 + 17;
        // The two boundary budgets prove total work is exactly `rows`: it
        // reaches `rows`, but never reaches `rows + 1`, including at batch end.
        for (budget, expected_yields) in [
            (1, rows.div_ceil(COARSE_WORK_BATCH_SIZE)),
            (rows, 1),
            (rows + 1, 0),
        ] {
            let mut stream = drain(
                vec![singleton_batch(rows)?],
                NonZeroUsize::new(budget).unwrap(),
            );
            let mut cx = Context::from_waker(futures::task::noop_waker_ref());
            let mut pending = 0;
            loop {
                match Pin::new(&mut stream).poll_next(&mut cx) {
                    Poll::Pending => {
                        pending += 1;
                        assert!(pending <= expected_yields, "budget={budget}");
                        assert_eq!(stream.metrics_for_test().input_batches.value(), 0);
                        assert_eq!(stream.metrics_for_test().input_rows.value(), 0);
                    }
                    Poll::Ready(None) => break,
                    other => panic!("expected empty output, got {other:?}"),
                }
            }
            assert_eq!(pending, expected_yields, "budget={budget}");
            let metrics = stream.metrics_for_test();
            assert_eq!(metrics.input_batches.value(), 1);
            assert_eq!(metrics.input_rows.value(), rows);
            assert_eq!(metrics.baseline_metrics.output_rows().value(), 0);
            assert!(stream.is_terminated());
        }
        Ok(())
    }
}