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

//! Resolve consecutive, unambiguous candidates against one physical Arrow batch.
//! Only the current, unpublished candidate can hand off to ordinary Lane.

mod ambiguous_lane;
mod batch_loop;
#[cfg(test)]
pub(super) mod regressions;
#[cfg(test)]
mod tests;

use super::*;
use crate::config::YieldPolicy;
use crate::core::AbsoluteRow;
use crate::execution::matching::ResolvedAfterMatchSkip;
use crate::execution::matching::row_loop::compiled_program::ExecutablePatternVariant;
use crate::execution::matching::row_loop::lane_scan::{
    ClassifierDemand, DirectLinearCursor, DirectScratch, LaneScanState,
    direct_payload::{DirectRouteCounters, direct_quantum},
};
use crate::execution::matching::row_loop::state::WorkGovernor;
use crate::execution::storage::accumulator::MatchAccumulator;
use crate::execution::storage::collection::BatchCollection;
use crate::nfa::AutomatonStateId;
use datafusion::execution::memory_pool::MemoryReservation;
use smallvec::SmallVec;
use std::ops::Range;

#[cfg(test)]
use ambiguous_lane::InlineLaneOutcome;

#[derive(Clone, Copy)]
enum BoolColKind {
    StaticSymbol,
    AndGuard,
    OrGuard,
}

enum DirectPublish {
    Published {
        next_match_number: u64,
        next_row: usize,
        winning_registers: usize,
    },
    Handoff,
}

pub(crate) enum ClosedSegmentOutcome {
    /// Post-skip cursor, which may exceed the candidate-start window's end.
    Complete(usize),
    Handoff {
        row_idx: usize,
        skip_direct: SkipDirect,
    },
    Yield(usize),
    Flush(usize),
}

impl ClosedSegmentOutcome {
    #[inline]
    fn handoff_at(row_idx: usize) -> Self {
        Self::Handoff {
            row_idx,
            skip_direct: SkipDirect::AtRow(row_idx),
        }
    }
}

enum DirectSymbolSource {
    Packed(usize),
    Constant,
    /// Physical BooleanArray columns: `(batch_col_idx, symbol_bit, kind)`.
    PhysicalBools(SmallVec<[(usize, u64, BoolColKind); 8]>),
}

#[derive(Clone, Copy)]
struct DirectSpan {
    partition_start: usize,
    start_row: usize,
    end_row: usize,
    read_end_row: usize,
    final_flush: bool,
    max_next_offset: usize,
    yield_mid_as_handoff: bool,
}

impl DirectSpan {
    #[inline]
    fn short_tail(
        &self,
        row_idx: usize,
        min_match_rows: usize,
        min_tail_rows: usize,
    ) -> Option<ClosedSegmentOutcome> {
        let remaining = self.read_end_row - row_idx;
        if self.final_flush {
            // Observable predicates still run on short final tails.
            (remaining < min_tail_rows).then_some(ClosedSegmentOutcome::Complete(row_idx))
        } else {
            (remaining < min_match_rows)
                .then_some(ClosedSegmentOutcome::handoff_at(row_idx))
        }
    }
}

enum BatchOutcome {
    NextBatch,
    Done(ClosedSegmentOutcome),
}

pub(super) enum DirectStop {
    Window,
    Yield,
    Handoff,
}

/// Amortizes direct-linear cursor, scratch, batch lookup, and route telemetry
/// across consecutive closed segments and windowed spans in one physical head.
pub(crate) struct ClosedDirectDriver<'a> {
    matcher: &'a PatternMatcher,
    variant: &'a Arc<ExecutablePatternVariant>,
    program: &'a Arc<LaneScanProgram>,
    collection: &'a BatchCollection,
    global_offset: usize,
    yield_policy: YieldPolicy,
    quantum: usize,
    start_state: AutomatonStateId,
    start_symbols_mask: u64,
    min_match_rows: usize,
    track_history: bool,
    classifier_demand: ClassifierDemand,
    symbol_source: DirectSymbolSource,
    eager_bitmap: u64,
    and_guarded_mask: u64,
    required_packed_mask: u64,
    history_configured: bool,
    cached_symbols: u64,
    cursor: DirectLinearCursor,
    scratch: DirectScratch,
    cached_batch: Option<(usize, usize, usize)>,
    routes: DirectRouteCounters,
}

impl<'a> ClosedDirectDriver<'a> {
    pub(crate) fn try_new(
        matcher: &'a PatternMatcher,
        collection: &'a BatchCollection,
        global_offset: usize,
        accumulator: &MatchAccumulator,
        yield_policy: YieldPolicy,
    ) -> Option<Self> {
        Self::try_new_for_variant(
            matcher,
            matcher.program.base_variant(),
            collection,
            global_offset,
            accumulator,
            yield_policy,
            true,
        )
    }

    fn try_new_for_variant(
        matcher: &'a PatternMatcher,
        variant: &'a Arc<ExecutablePatternVariant>,
        collection: &'a BatchCollection,
        global_offset: usize,
        accumulator: &MatchAccumulator,
        yield_policy: YieldPolicy,
        use_packed: bool,
    ) -> Option<Self> {
        #[cfg(test)]
        if matcher.generic_scan_forced_by_control() {
            return None;
        }
        if matcher.program.config().compact_paths_disabled
            || collection.num_batches() == 0
            || !accumulator.can_append_direct_winner()
        {
            return None;
        }
        let after_match_skip = matcher.program.after_match_skip();
        let program = variant.enabled_lane_scan_program(matcher)?;
        if !program.supports_direct_loop() {
            return None;
        }
        let automaton = variant.automaton();
        let min_match_rows = automaton.min_match_rows();
        if program.requires_partition_end() {
            return None;
        }
        let symbols = variant.symbol_execution_plan();
        let symbol_programs = variant.symbol_programs();
        let mut and_guarded_mask = 0u64;
        for &id in symbols.static_precheck_ids() {
            let index = id.index();
            if index < u64::BITS as usize
                && let Some(user) = symbol_programs[index].user()
                && !user.static_predicate_and_columns().is_empty()
                && user.static_predicate_or_columns().is_empty()
            {
                and_guarded_mask |= 1u64 << index;
            }
        }
        let symbol_source = if let Some(col) =
            matcher.program.packed_lane_column.filter(|_| use_packed)
        {
            DirectSymbolSource::Packed(col)
        } else {
            let mut entries = SmallVec::<[(usize, u64, BoolColKind); 8]>::new();
            let active_cols = variant.active_symbol_columns().columns();
            for symbol in symbols.physical_symbols() {
                let index = symbol.id.index();
                if index >= u64::BITS as usize {
                    return None;
                }
                let bit = 1u64 << index;
                if !symbol.publishes_match || symbols.eager_bitmap & bit != 0 {
                    continue;
                }
                let col = active_cols.iter().find(|c| c.id == symbol.id)?;
                entries.push((col.column.index(), bit, BoolColKind::StaticSymbol));
            }
            for &id in symbols.static_precheck_ids() {
                let index = id.index();
                if index >= u64::BITS as usize {
                    return None;
                }
                let user = symbol_programs[index].user()?;
                let bit = 1u64 << index;
                for &col in user.static_predicate_and_columns() {
                    entries.push((col.index(), bit, BoolColKind::AndGuard));
                }
                for &col in user.static_predicate_or_columns() {
                    entries.push((col.index(), bit, BoolColKind::OrGuard));
                }
            }
            if entries.is_empty() {
                DirectSymbolSource::Constant
            } else {
                DirectSymbolSource::PhysicalBools(entries)
            }
        };
        let start_state = automaton.nfa().start_state();
        let start_symbols_mask = program.state_symbols_mask(start_state);
        let cursor = DirectLinearCursor::new(program, start_state, global_offset)?;
        // Named skip targets need only the accepted first/last occurrence.
        // Row output may still demand runs independently of this projection.
        let mut classifier_demand = match after_match_skip {
            ResolvedAfterMatchSkip::ToFirst { symbol_id, .. }
            | ResolvedAfterMatchSkip::ToLast { symbol_id, .. } => {
                accumulator.compact_demand().with_symbol(*symbol_id)
            }
            _ => accumulator.compact_demand(),
        };
        // A forking stateful graph hands off prefixes to `run_ambiguous_lane`
        // via `DirectLinearCursor::seed_lane`; keep runs without per-row capture
        // tracking when candidates already track history so stateful DEFINE
        // prefixes are neither replayed from `cand_start` nor paying capture
        // updates on rejected candidates.
        if program.capacity.live_lanes > 1
            && program.payload_symbols != 0
            && classifier_demand != ClassifierDemand::Symbols(0)
        {
            classifier_demand = ClassifierDemand::All;
        }
        let quantum = direct_quantum(yield_policy);
        Some(Self {
            matcher,
            variant,
            program,
            collection,
            global_offset,
            yield_policy,
            quantum,
            start_state,
            start_symbols_mask,
            min_match_rows,
            track_history: classifier_demand != ClassifierDemand::Symbols(0),
            classifier_demand,
            symbol_source,
            eager_bitmap: symbols.eager_bitmap,
            and_guarded_mask,
            // NFA membership uses user IDs minus one; Lane reserves bit zero.
            // Packed eligibility clears bits for static symbols and necessary
            // AND-guarded dynamic symbols; OR guards are excluded from packed plans.
            required_packed_mask: (automaton.required_symbols_mask() << 1)
                & (!symbols.eager_bitmap | and_guarded_mask),
            history_configured: false,
            cached_symbols: 0,
            cursor,
            scratch: DirectScratch::default(),
            cached_batch: None,
            routes: DirectRouteCounters::default(),
        })
    }

    pub(crate) fn into_suffix_cursor(
        self,
    ) -> Option<(Arc<LaneScanProgram>, DirectLinearCursor)> {
        self.cursor
            .suffix_run
            .map(|_| (Arc::clone(self.program), self.cursor))
    }

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

    #[inline]
    fn min_tail_rows(&self) -> usize {
        if self.matcher.program.can_skip_candidate_evaluation() {
            self.min_match_rows
        } else {
            1
        }
    }

    #[expect(clippy::too_many_arguments)]
    pub(crate) fn drive_segment(
        &mut self,
        range: &Range<usize>,
        match_number: &mut u64,
        accumulator: &mut MatchAccumulator,
        lane_scan: &mut Option<LaneScanState>,
        lane_state_memory: &MemoryReservation,
        governor: &mut WorkGovernor,
        work: &mut usize,
    ) -> Result<ClosedSegmentOutcome> {
        let len = range.len();
        let part_start =
            self.global_offset.checked_add(range.start).ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE partition start exceeds usize".to_string(),
                )
            })?;
        let part_end = self.global_offset.checked_add(range.end).ok_or_else(|| {
            DataFusionError::ResourcesExhausted(
                "MATCH_RECOGNIZE partition end exceeds usize".to_string(),
            )
        })?;
        if len == 0
            || (len < self.min_match_rows
                && self.matcher.program.can_skip_candidate_evaluation())
        {
            *work += 1;
            return Ok(ClosedSegmentOutcome::Complete(part_end));
        }
        self.drive_span(
            DirectSpan {
                partition_start: part_start,
                start_row: part_start,
                end_row: part_end,
                read_end_row: part_end,
                final_flush: true,
                max_next_offset: 0,
                yield_mid_as_handoff: false,
            },
            match_number,
            accumulator,
            lane_scan,
            lane_state_memory,
            governor,
            work,
        )
    }

    #[expect(clippy::too_many_arguments)]
    fn drive_span(
        &mut self,
        span: DirectSpan,
        match_number: &mut u64,
        accumulator: &mut MatchAccumulator,
        lane_scan: &mut Option<LaneScanState>,
        lane_state_memory: &MemoryReservation,
        governor: &mut WorkGovernor,
        work: &mut usize,
    ) -> Result<ClosedSegmentOutcome> {
        // One closed driver may visit multiple partitions before yielding.
        // Retain a suffix only when the incoming span can resume that run.
        if !self.cursor.suffix_run.is_some_and(|(peel, end, _)| {
            peel >= span.partition_start
                && peel <= span.start_row
                && span.start_row < end
                && end <= span.read_end_row
        }) {
            self.cursor.suffix_run = None;
        }
        if !self.history_configured {
            self.cursor
                .configure_history(self.classifier_demand, lane_state_memory)?;
            self.history_configured = true;
        }
        let start_anchored = self.program.requires_partition_start();
        let min_tail_rows = self.min_tail_rows();
        let safe_read_end = span.read_end_row.saturating_sub(span.max_next_offset);
        let mut row_idx = span.start_row;

        while row_idx < span.end_row {
            if start_anchored && row_idx > span.partition_start {
                return Ok(ClosedSegmentOutcome::Complete(row_idx));
            }
            if let Some(outcome) =
                span.short_tail(row_idx, self.min_match_rows, min_tail_rows)
            {
                return Ok(outcome);
            }
            let rel = row_idx - self.global_offset;
            let (batch, batch_rel_start, batch_rel_end) = match self.cached_batch {
                Some((b, start, end)) if rel >= start && rel < end => (b, start, end),
                _ => {
                    let (b, local) = self.collection.locate(rel);
                    let start = rel - local;
                    let end = start + self.collection.batch(b).num_rows();
                    self.cached_batch = Some((b, start, end));
                    self.cached_symbols =
                        self.matcher.program.classification.as_ref().map_or(0, |c| {
                            c.clean_demanded_symbols(self.collection.batch(b))
                        });
                    (b, start, end)
                }
            };
            let batch_origin = self.global_offset + batch_rel_start;
            let batch_span_end = (self.global_offset + batch_rel_end).min(safe_read_end);
            if row_idx >= batch_span_end {
                return Ok(ClosedSegmentOutcome::handoff_at(row_idx));
            }
            absolute_row_from_usize(batch_span_end, "continuous batch end")?;
            let max_steps = batch_span_end - row_idx;
            if i64::try_from(max_steps).is_err()
                || (self.variant.requires_position_offset()
                    && u32::try_from(max_steps - 1).is_err())
            {
                return Ok(ClosedSegmentOutcome::handoff_at(row_idx));
            }
            let is_eof = span.final_flush && batch_span_end == span.read_end_row;
            let non_null = self
                .collection
                .bound_batch(batch)
                .is_some_and(|b| b.all_bound_non_null());
            let drive = match (non_null, self.track_history) {
                (true, false) => Self::drive_span_batch_typed::<true, false>,
                (true, true) => Self::drive_span_batch_typed::<true, true>,
                (false, false) => Self::drive_span_batch_typed::<false, false>,
                (false, true) => Self::drive_span_batch_typed::<false, true>,
            };
            match drive(
                self,
                batch,
                batch_origin,
                batch_span_end,
                is_eof,
                span,
                &mut row_idx,
                match_number,
                accumulator,
                lane_scan,
                lane_state_memory,
                governor,
                work,
            )? {
                BatchOutcome::NextBatch => continue,
                BatchOutcome::Done(outcome) => return Ok(outcome),
            }
        }
        Ok(ClosedSegmentOutcome::Complete(row_idx))
    }

    /// Phase 1 uses the ordinary direct scan and closes only at a rejected row
    /// or EOF. Phase 2 retains its capture start, end, and first-occurrence probe
    /// across both cooperative suspension and output flushing.
    fn drive_suffix_reuse_run(
        &mut self,
        start: usize,
        governor: &mut WorkGovernor,
        work: &mut usize,
        symbol: impl Fn(usize) -> u64,
    ) -> Result<Option<ClosedSegmentOutcome>> {
        let (mut peel, end, mut probe) = self.cursor.suffix_run.unwrap();

        // Searching each requested symbol only moves forward over this run:
        // O((1 + requested symbols) * run length), with no capture-list shifts.
        while peel < start && self.cursor.captures_mut().is_some() {
            let captures = self.cursor.captures_mut().expect("requested captures");
            let bit = symbol(peel);
            let done =
                captures.peel_prefix_row(bit, AbsoluteRow::new(peel as u64), || {
                    let probe_start = probe;
                    while probe < end && (probe == probe_start || *work < self.quantum) {
                        let found = symbol(probe) == bit;
                        *work += 1;
                        probe += 1;
                        if found {
                            return Ok(Some(AbsoluteRow::new((probe - 1) as u64)));
                        }
                    }
                    Ok(None)
                })?;
            if done {
                peel += 1;
                probe = peel + 1;
                *work += 1;
            }
            self.cursor.suffix_run = Some((peel, end, probe));
            if *work >= self.quantum {
                governor.record_completed(std::mem::take(work), || {
                    self.matcher.is_aborted()
                })?;
                if governor.take_yield_if_due_hot(self.yield_policy) {
                    return Ok(Some(ClosedSegmentOutcome::Yield(start)));
                }
            }
        }
        self.cursor.select_suffix_start(start);
        Ok(None)
    }
}

impl MatchAwareCandidates<'_, '_> {
    fn flush_buffered_for_direct_suffix(&mut self) -> Result<Option<DirectStop>> {
        let result = (|| {
            self.pending_output.try_reserve(1)?;
            let global_offset = self.scan_ctx.partition.global_row_offset;
            let governor = &mut self.scan_ctx.scan_state.governor;
            if let Some(batch) = self.out.flush_collection_with_work(
                self.setup.input_buffer,
                global_offset,
                self.setup.history_buffer,
                &mut |units| {
                    governor.record_completed(units, || self.matcher.is_aborted())
                },
            )? {
                self.pending_output.push_back(batch)?;
                Ok(Some(DirectStop::Yield))
            } else {
                Ok(None)
            }
        })();
        if result.is_err() {
            self.scan_ctx.direct_suffix = None;
        }
        result
    }

    pub(super) fn drive_direct_window(&mut self) -> Result<DirectStop> {
        // Finish output flushing before reborrowing the saved suffix.
        if self.scan_ctx.direct_suffix.is_some()
            && !self.out.can_append_direct_winner()
            && !self.out.is_empty()
            && let Some(stop) = self.flush_buffered_for_direct_suffix()?
        {
            return Ok(stop);
        }
        let variant = self
            .setup
            .variant
            .resolve(self.matcher.program.base_variant());
        if self.matcher.program.config().compact_paths_disabled
            || self.scan_ctx.partition.lane_disabled
            || !self.out.can_append_direct_winner()
            || self.row_idx < self.setup.provider_origin
            || self.row_idx >= self.end_row
            || self.scan_ctx.candidate_history.is_some()
        {
            return Ok(DirectStop::Handoff);
        }
        let Some(mut driver) = ClosedDirectDriver::try_new_for_variant(
            self.matcher,
            variant,
            self.setup.input_buffer,
            self.scan_ctx.partition.global_row_offset,
            self.out,
            self.yield_policy,
            self.setup.variant.is_base(),
        ) else {
            return Ok(DirectStop::Handoff);
        };
        if self.matcher.is_aborted() {
            return internal_err!("MATCH_RECOGNIZE execution cancelled");
        }
        let mut match_number = self.scan_ctx.partition.next_match_number;
        let mut work = 0usize;
        let span = DirectSpan {
            partition_start: self.scan_ctx.partition.absolute_partition_start,
            start_row: self.row_idx,
            end_row: self.end_row,
            read_end_row: self.read_end_row,
            final_flush: self.setup.final_flush,
            max_next_offset: self.out.max_next_offset().as_usize(),
            yield_mid_as_handoff: true,
        };
        let resources = self.scan_ctx.resources_mut();
        if let Some((program, cursor)) = resources.direct_suffix.take()
            && Arc::ptr_eq(&program, driver.program)
            && cursor.suffix_run.is_some_and(|(peel, end, _)| {
                peel <= span.start_row && span.start_row < end
            })
        {
            driver.cursor = cursor;
        }
        let outcome = driver.drive_span(
            span,
            &mut match_number,
            self.out,
            &mut resources.lane_scan,
            &resources.lane_state_memory,
            &mut resources.scan_state.governor,
            &mut work,
        );
        self.scan_ctx.partition.next_match_number = match_number;
        self.lane.merge_direct_routes(&driver.routes);
        // Keep captures local until both execution and its final work charge
        // succeed, even when the preceding candidate already finalized cleanup.
        let direct_suffix = if matches!(
            outcome,
            Ok(ClosedSegmentOutcome::Yield(_) | ClosedSegmentOutcome::Flush(_))
        ) {
            driver.into_suffix_cursor()
        } else {
            None
        };
        let charge = self
            .scan_ctx
            .scan_state
            .governor
            .record_completed(work, || self.matcher.is_aborted());
        let outcome = outcome?;
        charge?;
        self.scan_ctx.resources_mut().direct_suffix = direct_suffix;
        match outcome {
            ClosedSegmentOutcome::Complete(next_row) => {
                self.row_idx = next_row.max(self.end_row);
                Ok(DirectStop::Window)
            }
            ClosedSegmentOutcome::Yield(next_row) => {
                self.row_idx = next_row;
                Ok(DirectStop::Yield)
            }
            ClosedSegmentOutcome::Flush(next_row) => {
                self.row_idx = next_row;
                debug_assert!(self.scan_ctx.direct_suffix.is_some());
                self.flush_buffered_for_direct_suffix()?.ok_or_else(|| {
                    self.scan_ctx.direct_suffix = None;
                    datafusion::common::internal_datafusion_err!(
                        "MATCH_RECOGNIZE direct suffix flush requested on empty accumulator"
                    )
                })
            }
            ClosedSegmentOutcome::Handoff {
                row_idx: next_row,
                skip_direct,
            } => {
                self.row_idx = next_row;
                self.skip_direct = skip_direct;
                Ok(DirectStop::Handoff)
            }
        }
    }
}