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

//! Prepare admitted inputs and replay candidate histories at original update boundaries.

use std::fmt;
use std::ops::Range;
use std::sync::Arc;

use datafusion::arrow::array::{Array, ArrayRef, BooleanArray, make_array};
use datafusion::arrow::compute::FilterBuilder;
use datafusion::arrow::datatypes::DataType;
use datafusion::arrow::error::ArrowError;
use datafusion::arrow::record_batch::{RecordBatch, RecordBatchOptions};
use datafusion::common::cast::as_boolean_array;
use datafusion::physical_expr::PhysicalExpr;
use datafusion_common::utils::memory::RecordBatchMemoryCounter;
use datafusion_common::utils::proxy::VecAllocExt;
use datafusion_common::{DataFusionError, Result, ScalarValue, internal_err};
use datafusion_execution::memory_pool::MemoryReservation;
use datafusion_expr::Accumulator;
use datafusion_physical_expr::utils::collect_columns;
use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays;

use crate::core::SymbolId;
use crate::execution::common::coordinates::absolute_row_to_usize;
use crate::execution::common::memory::{reserved_vec, try_reserve_accounted};
use crate::execution::common::progress::{COARSE_WORK_BATCH_SIZE, CoarseWorkCounter};
use crate::execution::matching::path::{PathNode, PathNodeIndex};
use crate::execution::storage::collection::BatchCollection;
use crate::execution::storage::{
    canonical_interleave_type, contains_run_end_encoded, retype_gather_data,
};

use super::compiler::{
    BoundHistoryProgram, DeferredAggregateOperation, DeferredSymbolPredicateProgram,
};
use super::history::{HistoryPreparation, PreparedHistoryBatch};

/// Final path-local input for one Deferred aggregate operation.
#[derive(Debug)]
enum DeferredOperationDelta {
    /// The operation receives no update for this path segment.
    Skipped,
    /// Arguments ready to pass directly to the DataFusion accumulator.
    Values(Vec<ArrayRef>),
}

/// One path-local update delta applied at this node.
#[derive(Debug)]
struct PathDelta {
    /// Final updates aligned with the evaluator's aggregate operations.
    operations: Vec<DeferredOperationDelta>,
    /// Input rows represented by this delta, including rows skipped by every operation.
    row_count: usize,
    /// Capacity of the retained argument vectors and their unique Arrow buffers.
    _local_memory: MemoryReservation,
}

/// Scalars at the proposed row, retained through this check’s result evaluation.
#[derive(Debug)]
struct PredicateExtraState {
    values: Vec<ScalarValue>,
    _memory: MemoryReservation,
}

const WORK_CHECKPOINT_UNITS: usize = 256;

struct HistoryAccumulator {
    accumulator: Box<dyn Accumulator>,
    memory: MemoryReservation,
}

impl HistoryAccumulator {
    fn try_new(
        planned: &DeferredAggregateOperation,
        memory: MemoryReservation,
    ) -> Result<Self> {
        let accumulator = planned.lowered.aggregate.create_accumulator()?;
        memory.try_resize(accumulator.size())?;
        Ok(Self {
            accumulator,
            memory,
        })
    }
}

fn check_type(array: &ArrayRef, expected: &DataType, index: usize) -> Result<()> {
    let actual = array.data_type();
    if actual != expected {
        return Err(ArrowError::InvalidArgumentError(format!(
            "column types must match schema types, expected {expected} but found {actual} at column index {index}"
        )).into());
    }
    Ok(())
}

struct FilteredBatch {
    batch: RecordBatch,
    _memory: MemoryReservation,
}

fn filter_referenced_batch(
    batch: &RecordBatch,
    mask: &BooleanArray,
    exprs: &[Arc<dyn PhysicalExpr>],
    memory: &MemoryReservation,
) -> Result<FilteredBatch> {
    let mut referenced = vec![false; batch.num_columns()];
    let mut referenced_count = 0usize;
    let mut single_referenced = None;
    for expr in exprs {
        for column in collect_columns(expr) {
            if let Some(slot) = referenced.get_mut(column.index())
                && !*slot
            {
                *slot = true;
                referenced_count += 1;
                single_referenced = Some(column.index());
            }
        }
    }
    let mut builder = FilterBuilder::new(mask);
    if referenced_count > 1
        || single_referenced.is_some_and(|index| {
            FilterBuilder::is_optimize_beneficial(
                batch.schema_ref().field(index).data_type(),
            )
        })
    {
        builder = builder.optimize();
    }
    let predicate = builder.build();
    let selected = predicate.count();
    let batch_memory = memory.new_empty();
    let mut columns =
        reserved_vec(batch.num_columns(), &batch_memory, "deferred history")?;
    let mut counter = RecordBatchMemoryCounter::new();
    counter.count_batch(batch);
    for (index, column) in batch.columns().iter().enumerate() {
        let array = if referenced[index] {
            let filtered = if contains_run_end_encoded(column.data_type()) {
                // Arrow FILTER rebuilds REE fields canonically, including
                // children of structs. Normalize before it validates child
                // types, then restore the exact input fields and metadata.
                let canonical = canonical_interleave_type(column.data_type())?;
                let input =
                    make_array(retype_gather_data(column.to_data(), &canonical, false)?);
                let filtered = predicate.filter(input.as_ref())?;
                make_array(retype_gather_data(
                    filtered.to_data(),
                    column.data_type(),
                    true,
                )?)
            } else {
                predicate.filter(column.as_ref())?
            };
            let before = counter.memory_usage();
            counter.count_array(filtered.as_ref());
            batch_memory.try_grow(counter.memory_usage() - before)?;
            filtered
        } else {
            column.slice(0, selected)
        };
        columns.push(array);
    }
    let batch = RecordBatch::try_new_with_options(
        batch.schema(),
        columns,
        &RecordBatchOptions::new().with_row_count(Some(selected)),
    )?;
    Ok(FilteredBatch {
        batch,
        _memory: batch_memory,
    })
}

struct PreparedInputs {
    delta: PathDelta,
    extras: Option<PredicateExtraState>,
}

impl BoundHistoryProgram {
    fn prepare_inputs(
        &self,
        predicate: &DeferredSymbolPredicateProgram,
        reservation: &MemoryReservation,
        history: PreparedHistoryBatch,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<PreparedInputs> {
        let memory = reservation.new_empty();
        let PreparedHistoryBatch {
            memory: _input_memory,
            predicate_row,
            batch,
        } = history;
        let mut operations = reserved_vec(
            predicate.operation_indices.len(),
            &memory,
            "deferred history",
        )?;
        // Retained arguments keep counted buffers alive across all operations.
        let mut counter = RecordBatchMemoryCounter::new();

        // Apply each operation's SQL FILTER mask before evaluating its
        // inputs so filtered-out rows never trigger argument or ordering
        // errors or volatile calls, and reject non-Boolean masks directly.
        for &index in &predicate.operation_indices {
            let operation = &self.operations[index];
            let planned = &operation.planned;
            let entry = if let Some(filter_expr) = &planned.lowered.filter {
                let filter = filter_expr
                    .evaluate(&batch)?
                    .into_array_of_size(batch.num_rows())?;
                check_type(&filter, &operation.types[planned.input_exprs.len()], 0)?;
                let Some(mask) = filter.as_any().downcast_ref::<BooleanArray>() else {
                    return Err(DataFusionError::Execution(format!(
                        "History aggregate expected Boolean filter mask, found {}",
                        filter.data_type()
                    )));
                };
                if planned.input_exprs.is_empty() {
                    DeferredOperationDelta::Skipped
                } else {
                    match mask.true_count() {
                        0 => DeferredOperationDelta::Skipped,
                        selected if selected == batch.num_rows() => {
                            let arguments = evaluate_expressions_to_arrays(
                                &planned.input_exprs,
                                &batch,
                            )?;
                            DeferredOperationDelta::Values(arguments)
                        }
                        _ => {
                            let filtered = filter_referenced_batch(
                                &batch,
                                mask,
                                &planned.input_exprs,
                                &memory,
                            )?;
                            let arguments = evaluate_expressions_to_arrays(
                                &planned.input_exprs,
                                &filtered.batch,
                            )?;
                            DeferredOperationDelta::Values(arguments)
                        }
                    }
                }
            } else {
                let arguments =
                    evaluate_expressions_to_arrays(&planned.input_exprs, &batch)?;
                DeferredOperationDelta::Values(arguments)
            };
            if let DeferredOperationDelta::Values(arguments) = &entry {
                memory.try_grow(arguments.allocated_size())?;
                let before = counter.memory_usage();
                for (i, (array, ty)) in arguments.iter().zip(&operation.types).enumerate()
                {
                    check_type(array, ty, i)?;
                    counter.count_array(array.as_ref());
                }
                memory.try_grow(counter.memory_usage() - before)?;
            }
            operations.push(entry);
            // Give the governor a cancellation/deadline checkpoint even when an
            // opaque expression receives only one row.
            completed(batch.num_rows().max(WORK_CHECKPOINT_UNITS))?;
        }

        let delta = PathDelta {
            operations,
            row_count: batch.num_rows(),
            _local_memory: memory,
        };
        let extras = if let Some(row) = predicate_row
            && !predicate.extra_ordinals.is_empty()
        {
            let memory = reservation.new_empty();
            let mut values = reserved_vec(
                predicate.extra_ordinals.len(),
                &memory,
                "deferred history",
            )?;
            let mut counter = CoarseWorkCounter::new();
            let result: Result<()> = (|| {
                for &column in &predicate.extra_ordinals {
                    let array = batch.column(column);
                    let value = ScalarValue::try_from_array(array, row)?;
                    memory.try_grow(value.size() - size_of::<ScalarValue>())?;
                    values.push(value);
                    counter.complete_one(&mut *completed)?;
                }
                Ok(())
            })();
            counter.finish_result(result, completed)?;
            Some(PredicateExtraState {
                values,
                _memory: memory,
            })
        } else {
            None
        };
        Ok(PreparedInputs { delta, extras })
    }
}

/// Each accepted prefix owns its already filtered and evaluated UDAF arguments.
/// Accumulators are opaque. At a fork, replay these values in original row
/// order; ordinary extensions use the accumulator state already in place.
struct Prefix {
    node: PathNodeIndex,
    // Deltas use this symbol's dense operation order, including shared operations.
    symbol: SymbolId,
    parent: Option<usize>,
    deltas: Vec<PathDelta>,
}

struct Pending {
    node: PathNodeIndex,
    symbol: SymbolId,
    match_number: u64,
    parent: Option<usize>,
    path: Vec<PathNodeIndex>,
    raw_replay_to: Option<PathNodeIndex>,
    tail: Range<usize>,
    saved: Vec<PathDelta>,
    phase: Phase,
    extras: Option<PredicateExtraState>,
    ancestors: Vec<usize>,
    memory: MemoryReservation,
}

// The gathered rows and prepared physical inputs survive cooperative pauses.
#[allow(clippy::large_enum_variant)]
enum Phase {
    Start,
    Trace(Option<PathNodeIndex>),
    NextChunk,
    Gather(HistoryPreparation),
    Prepare(PreparedHistoryBatch),
    Ancestors(Option<usize>),
    Reset,
    Replay { prefix: usize, chunk: usize },
    Result,
}

/// Private to one scan and its path arena. One pending verdict owns every
/// intermediate mutation; the caller cannot publish a provisional candidate.
pub(crate) struct CandidateHistory {
    program: Arc<BoundHistoryProgram>,
    operations: Vec<HistoryAccumulator>,
    prefixes: Vec<Prefix>,
    boundaries: Vec<PathNodeIndex>,
    current: Option<PathNodeIndex>,
    current_symbol: Option<SymbolId>,
    match_number: Option<u64>,
    #[cfg(test)]
    gathered_rows: u64,
    #[cfg(test)]
    replayed_rows: u64,
    pending: Option<Pending>,
    memory: MemoryReservation,
}

impl fmt::Debug for CandidateHistory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CandidateHistory")
            .field("prefixes", &self.prefixes.len())
            .field("pending", &self.pending.is_some())
            .finish()
    }
}

impl CandidateHistory {
    pub(super) fn new(
        program: Arc<BoundHistoryProgram>,
        memory: &MemoryReservation,
    ) -> Result<Self> {
        let memory = memory.new_empty();
        memory.try_grow(size_of::<CandidateHistory>())?;
        Ok(Self {
            program,
            operations: Vec::new(),
            prefixes: Vec::new(),
            boundaries: Vec::new(),
            current: None,
            current_symbol: None,
            match_number: None,
            #[cfg(test)]
            gathered_rows: 0,
            #[cfg(test)]
            replayed_rows: 0,
            pending: None,
            memory,
        })
    }

    #[cfg(test)]
    pub(crate) fn gathered_rows(&self) -> u64 {
        self.gathered_rows
    }
    #[cfg(test)]
    pub(crate) fn replayed_rows(&self) -> u64 {
        self.replayed_rows
    }

    #[cfg(test)]
    pub(crate) fn boundary_storage(&self) -> (usize, usize) {
        (self.boundaries.len(), self.boundaries.allocated_size())
    }

    fn apply(
        state: &mut HistoryAccumulator,
        values: &DeferredOperationDelta,
    ) -> Result<()> {
        if let DeferredOperationDelta::Values(arguments) = values {
            state.accumulator.update_batch(arguments)?;
        }
        state.memory.try_resize(state.accumulator.size())
    }

    pub(crate) fn begin(
        &mut self,
        node: PathNodeIndex,
        symbol: SymbolId,
        match_number: u64,
    ) -> Result<()> {
        if self.pending.is_some() {
            return internal_err!("a candidate history check is already active");
        }
        // The arena appends nodes in index order. A truncate/reuse can never
        // inherit the discarded node's volatile values, even at the same row.
        if self.match_number != Some(match_number) {
            self.truncate(0);
            self.match_number = Some(match_number);
        }
        if self.current.is_some_and(|current| current >= node)
            || self.prefixes.last().is_some_and(|p| p.node >= node)
            || self
                .boundaries
                .last()
                .is_some_and(|&existing| existing >= node)
        {
            self.truncate(node as usize);
        }
        self.pending = Some(Pending {
            node,
            symbol,
            match_number,
            parent: None,
            path: Vec::new(),
            raw_replay_to: None,
            tail: 0..0,
            saved: Vec::new(),
            phase: Phase::Start,
            extras: None,
            ancestors: Vec::new(),
            memory: self.memory.new_empty(),
        });
        Ok(())
    }

    pub(crate) fn discard(&mut self, node: PathNodeIndex) {
        self.truncate(node as usize);
    }

    /// Forget every provisional arena index at or after the rollback point.
    /// A fresh arena must receive a fresh CandidateHistory.
    pub(crate) fn truncate(&mut self, first_removed: usize) {
        self.boundaries.truncate(
            self.boundaries
                .partition_point(|&node| (node as usize) < first_removed),
        );
        let retained = self
            .prefixes
            .partition_point(|prefix| (prefix.node as usize) < first_removed);
        let released = self.prefixes[retained..]
            .iter()
            .map(|prefix| prefix.deltas.allocated_size())
            .sum();
        self.prefixes.truncate(retained);
        self.memory.shrink(released);
        if self
            .current
            .is_some_and(|node| node as usize >= first_removed)
        {
            self.current = None;
        }
        if self
            .pending
            .as_ref()
            .is_some_and(|pending| pending.node as usize >= first_removed)
        {
            self.pending = None;
            self.current = None;
        }
    }

    pub(crate) fn advance(
        &mut self,
        collection: &BatchCollection,
        arena: &[PathNode],
        head: usize,
        partition_end: usize,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<Option<bool>> {
        let Some(mut check) = self.pending.take() else {
            return internal_err!("no candidate history check to advance");
        };
        let program = Arc::clone(&self.program);
        let predicate = program
            .predicates
            .get(check.symbol.index())
            .and_then(Option::as_ref)
            .ok_or_else(|| {
                datafusion_common::internal_datafusion_err!(
                    "candidate predicate slot {} is outside its program",
                    check.symbol
                )
            })?;
        let lookahead = predicate.max_lookahead_rows;
        completed(1)?;
        check.phase = match check.phase {
            Phase::Start => {
                if predicate.save_history_inputs && lookahead.is_zero() {
                    try_reserve_accounted(
                        &mut self.prefixes,
                        &self.memory,
                        1,
                        "candidate history prefixes",
                    )?;
                }
                let node = arena.get(check.node as usize).ok_or_else(|| {
                    datafusion_common::internal_datafusion_err!(
                        "candidate node outside its arena"
                    )
                })?;
                let after = absolute_row_to_usize(node.step.row, "candidate lookahead")?
                    .checked_add(1)
                    .ok_or_else(|| {
                        datafusion_common::internal_datafusion_err!(
                            "candidate row overflow"
                        )
                    })?;
                check.tail = after.max(head)
                    ..after
                        .saturating_add(lookahead.as_usize())
                        .min(partition_end);
                Phase::Trace(Some(check.node))
            }
            Phase::Trace(mut next) => {
                // Stop at the live prefix or an accepted saved prefix. An
                // intervening Static/Incremental row need not have requested a
                // check of its own. Read its chosen label from the same arena.
                let mut phase = None;
                for _ in 0..COARSE_WORK_BATCH_SIZE {
                    let Some(index) = next else {
                        phase = Some(Phase::Reset);
                        break;
                    };
                    if index != check.node && lookahead.is_zero() {
                        if check.raw_replay_to.is_none()
                            && self.boundaries.binary_search(&index).is_ok()
                            && arena[index as usize].step.sym.to_index()
                                == check.symbol.index()
                        {
                            check.raw_replay_to = Some(index);
                        }
                        let saved = predicate
                            .save_history_inputs
                            .then(|| {
                                self.prefixes
                                    .binary_search_by_key(&index, |p| p.node)
                                    .ok()
                                    .filter(|&saved| {
                                        self.prefixes[saved].symbol == check.symbol
                                    })
                            })
                            .flatten();
                        // A different symbol has its own accumulator set, even
                        // when some logical operations share a binding.
                        let current = self.current == Some(index)
                            && self.current_symbol == Some(check.symbol);
                        if current || saved.is_some() {
                            check.parent = saved;
                            phase = Some(if current {
                                Phase::NextChunk
                            } else {
                                Phase::Ancestors(saved)
                            });
                            break;
                        }
                    }
                    let node = arena.get(index as usize).ok_or_else(|| {
                        datafusion_common::internal_datafusion_err!(
                            "candidate ancestor outside its arena"
                        )
                    })?;
                    if let Some(parent) = node.prev
                        && (parent >= index
                            || arena[parent as usize].depth.checked_add(1)
                                != Some(node.depth))
                    {
                        return internal_err!("invalid candidate ancestry at {index}");
                    }
                    try_reserve_accounted(
                        &mut check.path,
                        &check.memory,
                        1,
                        "candidate history path",
                    )?;
                    check.path.push(index);
                    completed(1)?;
                    next = if predicate.operation_indices.is_empty() {
                        None
                    } else {
                        node.prev
                    };
                }
                phase.unwrap_or(Phase::Trace(next))
            }
            Phase::Ancestors(mut next) => {
                for _ in 0..COARSE_WORK_BATCH_SIZE {
                    let Some(index) = next else { break };
                    try_reserve_accounted(
                        &mut check.ancestors,
                        &check.memory,
                        1,
                        "history replay prefix",
                    )?;
                    check.ancestors.push(index);
                    completed(1)?;
                    next = self.prefixes[index].parent;
                }
                if next.is_some() {
                    Phase::Ancestors(next)
                } else {
                    Phase::Reset
                }
            }
            Phase::Reset => {
                self.current = None;
                while self.operations.pop().is_some() {
                    completed(1)?;
                }
                try_reserve_accounted(
                    &mut self.operations,
                    &self.memory,
                    predicate.operation_indices.len(),
                    "deferred accumulators",
                )?;
                self.current_symbol = Some(check.symbol);
                for &operation in &predicate.operation_indices {
                    self.operations.push(HistoryAccumulator::try_new(
                        &self.program.operations[operation].planned,
                        self.memory.new_empty(),
                    )?);
                    completed(1)?;
                }
                match check.ancestors.pop() {
                    Some(prefix) => Phase::Replay { prefix, chunk: 0 },
                    None => Phase::NextChunk,
                }
            }
            Phase::Replay { prefix, chunk } => {
                // Saved prefixes always contain nonempty, bounded delta chunks.
                let deltas = &self.prefixes[prefix].deltas;
                let delta = &deltas[chunk];
                #[cfg(test)]
                {
                    self.replayed_rows += delta.row_count as u64;
                }
                for (operation, value) in delta.operations.iter().enumerate() {
                    Self::apply(&mut self.operations[operation], value)?;
                    completed(delta.row_count.max(1))?;
                }
                if chunk + 1 < deltas.len() {
                    Phase::Replay {
                        prefix,
                        chunk: chunk + 1,
                    }
                } else {
                    check.ancestors.pop().map_or(Phase::NextChunk, |prefix| {
                        Phase::Replay { prefix, chunk: 0 }
                    })
                }
            }
            Phase::NextChunk => {
                self.current = None;
                if check.path.is_empty() && check.tail.is_empty() {
                    Phase::Result
                } else {
                    let mut start =
                        check.path.len().saturating_sub(COARSE_WORK_BATCH_SIZE);
                    // Recreate the same update_batch boundaries on a branch switch.
                    // A floating SUM or opaque UDAF can distinguish different
                    // groupings of identical inputs. Four bytes per checked node
                    // suffice for deterministic inputs; volatile inputs own deltas.
                    if check.raw_replay_to.is_some() && lookahead.is_zero() {
                        for index in (start..check.path.len()).rev() {
                            if self.boundaries.binary_search(&check.path[index]).is_ok()
                                && arena[check.path[index] as usize].step.sym.to_index()
                                    == check.symbol.index()
                            {
                                start = index;
                                break;
                            }
                        }
                    }
                    let nodes = &check.path[start..];
                    let following = if nodes.is_empty() {
                        let end = check
                            .tail
                            .start
                            .saturating_add(COARSE_WORK_BATCH_SIZE)
                            .min(check.tail.end);
                        let range = check.tail.start..end;
                        check.tail.start = end;
                        range
                    } else {
                        0..0
                    };
                    let gather = HistoryPreparation::candidate_chunk(
                        &self.program.history,
                        collection,
                        &self.program.encoder,
                        arena,
                        nodes,
                        following,
                        check.node,
                        check.match_number,
                        head,
                        partition_end,
                        &self.memory,
                        completed,
                    )?;
                    #[cfg(test)]
                    if let Some(previous) = check.raw_replay_to {
                        self.replayed_rows +=
                            nodes.iter().filter(|&&node| node <= previous).count() as u64;
                    }
                    check.path.truncate(start);
                    Phase::Gather(gather)
                }
            }
            Phase::Gather(mut gather) => {
                if let Some(history) =
                    gather.advance(&self.program.history, collection, completed)?
                {
                    let rows = history.batch.num_rows();
                    #[cfg(test)]
                    {
                        self.gathered_rows += rows as u64;
                    }
                    if rows == 0 {
                        Phase::NextChunk
                    } else {
                        Phase::Prepare(history)
                    }
                } else {
                    Phase::Gather(gather)
                }
            }
            Phase::Prepare(history) => {
                let prepared = self.program.prepare_inputs(
                    predicate,
                    &self.memory,
                    history,
                    completed,
                )?;
                if let Some(extras) = prepared.extras {
                    check.extras = Some(extras);
                }
                let delta = prepared.delta;
                for (operation, value) in delta.operations.iter().enumerate() {
                    Self::apply(&mut self.operations[operation], value)?;
                    completed(delta.row_count.max(1))?;
                }
                if predicate.save_history_inputs && lookahead.is_zero() {
                    try_reserve_accounted(
                        &mut check.saved,
                        &check.memory,
                        1,
                        "candidate saved input blocks",
                    )?;
                    check.saved.push(delta);
                }
                Phase::NextChunk
            }
            Phase::Result => {
                let mut columns = reserved_vec(
                    predicate.predicate_schema.fields().len(),
                    &check.memory,
                    "deferred history",
                )?;
                let extras = check.extras.iter().flat_map(|state| &state.values);
                let results = self.operations.iter_mut().map(|state| {
                    let value = state.accumulator.evaluate()?;
                    state.memory.try_resize(state.accumulator.size())?;
                    value.to_array()
                });
                for array in results.chain(extras.map(ScalarValue::to_array)) {
                    let array = array?;
                    check.memory.try_grow(array.get_array_memory_size())?;
                    columns.push(array);
                    completed(1)?;
                }
                let batch = RecordBatch::try_new_with_options(
                    Arc::clone(&predicate.predicate_schema),
                    columns,
                    &RecordBatchOptions::new().with_row_count(Some(1)),
                )?;
                let accepted = if let Some(predicate) = &predicate.predicate {
                    let result = predicate.evaluate(&batch)?.into_array(1)?;
                    let values = as_boolean_array(&result)?;
                    !values.is_null(0) && values.value(0)
                } else {
                    true
                };
                if accepted && lookahead.is_zero() {
                    self.current = Some(check.node);
                    self.current_symbol = Some(check.symbol);
                    if !predicate.save_history_inputs
                        && !predicate.operation_indices.is_empty()
                    {
                        try_reserve_accounted(
                            &mut self.boundaries,
                            &self.memory,
                            1,
                            "history update boundaries",
                        )?;
                        self.boundaries.push(check.node);
                    }
                }
                if accepted && !check.saved.is_empty() {
                    let saved_bytes = check.saved.allocated_size();
                    check.memory.shrink(saved_bytes);
                    self.memory.grow(saved_bytes);
                    self.prefixes.push(Prefix {
                        node: check.node,
                        symbol: check.symbol,
                        parent: check.parent,
                        deltas: check.saved,
                    });
                }
                return Ok(Some(accepted));
            }
        };
        self.pending = Some(check);
        Ok(None)
    }
}

#[cfg(test)]
#[path = "tests/operation_delta.rs"]
mod operation_delta_tests;

#[cfg(test)]
#[path = "tests/preparation_memory.rs"]
mod preparation_memory_tests;

#[cfg(test)]
#[path = "tests/preparation.rs"]
mod preparation_tests;