datafusion-match-recognize 0.56.1

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

//! Aggregate and predicate kernel for row-loop transition evaluation.
//!
//! For each candidate transition, the engine updates managed aggregates and
//! invokes the predicate evaluator chosen during construction. Supporting
//! modules read bound inputs, evaluate compiled predicates or Hybrid guards,
//! decode values for physical-expression fallback, and record the effects of a
//! successful transition.

mod physical_expr_fallback;
mod transition_eval;

pub(crate) use transition_eval::checked_position_offset;

use crate::core::{AbsoluteRow, AggregateValue, SymbolId};
use datafusion::arrow::array::ArrayRef;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::Result;
use datafusion::execution::memory_pool::MemoryReservation;
use datafusion::scalar::ScalarValue;

use super::compiled_program::ExecutablePatternVariant;
use super::predicate_decision::PredicateCacheProbe;
use super::predicate_decision::TransitionDecision;
use super::provider::{cache_single_row_batch, clear_argument_slot};
use crate::execution::matching::ResolvedInputColumn;
use crate::execution::matching::row_loop::arena::SingleRowArrayArena;
use crate::execution::matching::{ExecutableUserSymbolProgram, PatternMatcher};
use crate::execution::storage::collection::BatchCollection;

/// Reusable row values, aggregate results, and temporary evaluation buffers.
/// Keeping them separate lets the row loop borrow the engine and its buffers
/// independently.
#[derive(Debug, Default)]
pub(crate) struct ScratchState {
    pub(crate) scratch_agg_results: Vec<ScalarValue>,
    pub(crate) scratch_agg_results_primitive: Vec<AggregateValue>,
    pub(crate) scratch_agg_columns: Vec<ArrayRef>,
    pub(crate) array_arena: SingleRowArrayArena,
    pub(crate) pre_evaluated_aggs: Vec<Vec<ArrayRef>>,
}

#[derive(Debug)]
pub(crate) struct EvaluationState {
    pub(crate) current_match_start_row: AbsoluteRow,
    pub(crate) current_match_sequence_number: i64,
    pub(crate) current_excluded: bool,
}

/// One symbol-slot cache entry for a transition-local DEFINE verdict.
#[derive(Debug, Clone, Copy)]
pub(crate) struct DefineCacheEntry {
    pub(crate) match_start: AbsoluteRow,
    pub(crate) generation: u32,
    pub(crate) excluded: bool,
    pub(crate) outcome: TransitionDecision,
}

impl DefineCacheEntry {
    const EMPTY: Self = Self {
        match_start: AbsoluteRow::ZERO,
        generation: 0,
        excluded: false,
        outcome: TransitionDecision::Reject,
    };
}

#[derive(Debug, Default)]
pub(crate) struct DefineCacheState {
    pub(crate) define_cache: Vec<DefineCacheEntry>,
    pub(crate) define_cache_gen: u32,
}

impl DefineCacheState {
    #[cfg(test)]
    pub(crate) fn initialize_define_cache(&mut self, symbol_count: usize) {
        self.define_cache = vec![DefineCacheEntry::EMPTY; symbol_count];
    }

    pub(crate) fn invalidate_define_cache(&mut self) {
        self.define_cache.fill(DefineCacheEntry::EMPTY);
    }

    pub(crate) fn proposed_generation(&mut self) -> u32 {
        let generation = self.define_cache_gen.wrapping_add(1);
        if generation != 0 {
            return generation;
        }
        self.invalidate_define_cache();
        1
    }
}

#[cfg(test)]
#[derive(Debug, Default)]
pub(crate) struct DebugCounters {
    /// Number of expensive row preparations observed by a focused test.
    pub(crate) row_preparations: u64,
    /// Number of row rebindings observed after resumption.
    pub(crate) row_resumptions: u64,
    /// Number of reusable DEFINE-cache hits observed by a focused test.
    pub(crate) define_cache_hits: u64,
    /// Number of DEFINE-cache misses observed by a focused test.
    pub(crate) define_cache_misses: u64,
}

#[derive(Debug)]
pub(crate) struct AggregateEngineState {
    pub(crate) scratch: ScratchState,
    pub(crate) evaluation: EvaluationState,
    pub(crate) define_cache_state: DefineCacheState,
    pub(crate) primitive_memory: MemoryReservation,
    #[cfg(test)]
    pub(crate) debug_counters: DebugCounters,
    // Drop cached argument arrays before releasing their reservation.
    pub(crate) argument_memory: MemoryReservation,
}

impl Default for AggregateEngineState {
    fn default() -> Self {
        Self::new(
            super::state_growth::new_unbounded_state_memory().new_empty(),
            0,
        )
    }
}

impl AggregateEngineState {
    pub(crate) fn new(state_memory: MemoryReservation, n_symbols: usize) -> Self {
        Self {
            argument_memory: state_memory.new_empty(),
            primitive_memory: state_memory.new_empty(),
            scratch: ScratchState {
                scratch_agg_results: Vec::new(),
                scratch_agg_results_primitive: Vec::new(),
                scratch_agg_columns: Vec::new(),
                array_arena: SingleRowArrayArena::with_reservation(
                    state_memory,
                    Default::default(),
                ),
                pre_evaluated_aggs: Vec::new(),
            },
            evaluation: EvaluationState::default(),
            define_cache_state: DefineCacheState {
                define_cache: vec![DefineCacheEntry::EMPTY; n_symbols],
                define_cache_gen: 0,
            },
            #[cfg(test)]
            debug_counters: DebugCounters::default(),
        }
    }

    pub(crate) fn reset(&mut self) {
        self.scratch.array_arena.clear();
        self.scratch.scratch_agg_results.clear();
        self.define_cache_state.invalidate_define_cache();
        self.scratch.scratch_agg_results_primitive.clear();
        self.scratch.scratch_agg_columns.clear();
        self.clear_argument_arrays();
        self.evaluation.current_match_sequence_number = 1;
    }

    /// Release row arrays while retaining vector capacity for reuse.
    fn clear_argument_arrays(&mut self) {
        for arguments in &mut self.scratch.pre_evaluated_aggs {
            arguments.clear();
        }
        self.argument_memory.free();
    }

    pub(crate) fn reset_partition_generation(&mut self) {
        self.define_cache_state.define_cache_gen = 0;
        self.scratch.pre_evaluated_aggs = Vec::new();
        self.argument_memory.free();
    }
}

impl Default for EvaluationState {
    fn default() -> Self {
        Self {
            current_match_start_row: AbsoluteRow::ZERO,
            current_match_sequence_number: 1,
            current_excluded: false,
        }
    }
}

/// Updates managed aggregates and evaluates Incremental or Hybrid conditions.
pub(crate) struct AggregateEngine<'a, 'state> {
    pub(crate) matcher: &'a PatternMatcher,
    pub(crate) variant: &'a ExecutablePatternVariant,
    pub(crate) input_buffer: &'a BatchCollection,
    pub(crate) managed_agg_indices: &'a [ResolvedInputColumn],

    // Mutable state
    pub(crate) state: &'state mut AggregateEngineState,
    pub(crate) define_cache_gen: u32,

    // Context
    pub(crate) partition_start_row: usize,
    pub(crate) global_row_offset: usize,
    pub(crate) next_match_number: u64,

    // Row-local state (updated via `update_row`)
    pub(crate) current_row: usize,
    pub(crate) bound_row:
        Option<crate::execution::storage::bound_columns::BoundBatchRow<'a>>,
    pub(crate) cached_batch: Option<RecordBatch>,
    pub(crate) cached_batch_location: Option<(usize, usize)>,
}

impl<'a, 'state> AggregateEngine<'a, 'state> {
    #[allow(
        clippy::too_many_arguments,
        reason = "constructor binds disjoint borrowed hot-loop state without an allocating owner wrapper"
    )]
    pub fn new(
        matcher: &'a PatternMatcher,
        variant: &'a ExecutablePatternVariant,
        input_buffer: &'a BatchCollection,
        managed_agg_indices: &'a [ResolvedInputColumn],
        state: &'state mut AggregateEngineState,
        define_cache_gen: u32,
        partition_start_row: usize,
        global_row_offset: usize,
        next_match_number: u64,
    ) -> Self {
        Self {
            matcher,
            variant,
            input_buffer,
            managed_agg_indices,
            state,
            define_cache_gen,
            partition_start_row,
            global_row_offset,
            next_match_number,
            current_row: 0,
            bound_row: None,
            cached_batch: None,
            cached_batch_location: None,
        }
    }

    /// FIRST can address its candidate's first row in the current Arrow head
    /// whenever the 1-based match sequence fits the row's local prefix.
    #[inline]
    pub(crate) fn bound_candidate_start(
        &self,
    ) -> Option<crate::execution::storage::bound_columns::BoundBatchRow<'a>> {
        self.bound_row?;
        let (batch, local) = self.cached_batch_location?;
        let seq =
            usize::try_from(self.state.evaluation.current_match_sequence_number).ok()?;
        self.input_buffer
            .bound_row(batch, local.checked_sub(seq.checked_sub(1)?)?)
    }

    pub(crate) fn probe_predicate_cache(
        &mut self,
        program: &ExecutableUserSymbolProgram,
        symbol: SymbolId,
        match_start: AbsoluteRow,
        excluded: bool,
    ) -> PredicateCacheProbe {
        let probe = PredicateCacheProbe::probe(
            program.define_cache(),
            self.matcher.aggregate_backend_set().is_registers_only(),
            || self.check_cache(symbol, match_start, excluded),
        );
        #[cfg(test)]
        if let Some(counter) = match probe {
            PredicateCacheProbe::Hit(_) => {
                Some(&mut self.state.debug_counters.define_cache_hits)
            }
            PredicateCacheProbe::Miss => {
                Some(&mut self.state.debug_counters.define_cache_misses)
            }
            PredicateCacheProbe::Disabled => None,
        } {
            *counter = counter.saturating_add(1);
        }
        probe
    }

    pub(crate) fn prepare_or_resume_transition_row<Report>(
        &mut self,
        current_row: usize,
        partition_len: usize,
        prepare: bool,
        completed: &mut Report,
    ) -> Result<()>
    where
        Report: FnMut(usize) -> Result<()>,
    {
        let generation = self.define_cache_gen;
        if !prepare && self.state.define_cache_state.define_cache_gen != generation {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE DEFINE cache generation changed across resume"
            );
        }
        if prepare {
            self.update_row(current_row, partition_len, generation, completed)?;
            self.state.define_cache_state.define_cache_gen = generation;
        } else {
            self.resume_row(current_row, generation)?;
        }
        Ok(())
    }

    /// Physical fallback for columns absent from the bound batch table.
    pub(crate) fn input_row(&self) -> Result<(&'a RecordBatch, usize)> {
        self.cached_batch_location
            .map(|(batch, row)| (self.input_buffer.batch(batch), row))
            .ok_or_else(|| {
                datafusion::common::internal_datafusion_err!(
                    "missing physical VM input row"
                )
            })
    }

    #[inline]
    pub(crate) fn input_is_null(&self, column: usize) -> Result<bool> {
        if let Some(value) = self.bound_row.and_then(|row| row.is_null(column)) {
            return Ok(value);
        }
        let (batch, row) = self.input_row()?;
        Ok(crate::execution::common::nulls::is_logically_null(
            batch.column(column).as_ref(),
            row,
        ))
    }

    #[inline]
    pub(crate) fn input_word(&self, column: usize, force_float: bool) -> Result<u64> {
        if let Some(value) = self.bound_row.and_then(|row| row.word(column, force_float))
        {
            return Ok(value);
        }
        let (batch, row) = self.input_row()?;
        Ok(crate::execution::storage::bound_columns::unbound_word(
            batch.column(column),
            row,
            force_float,
        ))
    }

    #[inline]
    pub(crate) fn input_decimal(&self, column: usize) -> Result<(u64, u64)> {
        if let Some(value) = self.bound_row.and_then(|row| row.decimal(column)) {
            return Ok((value as u64, (value >> 64) as u64));
        }
        let (batch, row) = self.input_row()?;
        Ok(Self::extract_decimal128_words(batch.column(column), row))
    }

    fn collection_row_idx(&self, partition_row_idx: usize) -> Result<usize> {
        partition_row_idx
            .checked_add(self.partition_start_row)
            .ok_or_else(|| {
                datafusion::common::DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE collection row coordinate exceeds the platform usize boundary"
                        .to_string(),
                )
            })
    }

    fn bind_row(&mut self, current_row: usize, define_cache_gen: u32) -> Result<usize> {
        self.current_row = current_row;
        self.define_cache_gen = define_cache_gen;

        let current_rel = self.collection_row_idx(current_row)?;
        let new_location = if current_rel < self.input_buffer.num_rows() {
            let (batch_idx, local_row) = self.input_buffer.locate(current_rel);
            Some((batch_idx, local_row))
        } else {
            None
        };
        self.cached_batch_location = new_location;
        self.bound_row =
            new_location.and_then(|(batch, row)| self.input_buffer.bound_row(batch, row));
        Ok(current_rel)
    }

    /// Rebind ephemeral row coordinates after a cooperative pause.
    ///
    /// Prepared accumulator arguments and predicate decisions live in
    /// `AggregateEngineState` and remain valid for the row.
    pub fn resume_row(
        &mut self,
        current_row: usize,
        define_cache_gen: u32,
    ) -> Result<()> {
        self.bind_row(current_row, define_cache_gen)?;
        #[cfg(test)]
        {
            self.state.debug_counters.row_resumptions =
                self.state.debug_counters.row_resumptions.saturating_add(1);
        }
        Ok(())
    }

    pub fn update_row<Report>(
        &mut self,
        current_row: usize,
        partition_len: usize,
        define_cache_gen: u32,
        report_completed_work: &mut Report,
    ) -> Result<()>
    where
        Report: FnMut(usize) -> Result<()>,
    {
        let current_rel = self.bind_row(current_row, define_cache_gen)?;
        #[cfg(test)]
        {
            self.state.debug_counters.row_preparations =
                self.state.debug_counters.row_preparations.saturating_add(1);
        }

        self.cached_batch = None;
        if self
            .matcher
            .aggregate_backend_set()
            .requires_accumulator_state()
            && current_row < partition_len
        {
            if self.cached_batch_location.is_none() {
                return datafusion::common::internal_err!(
                    "MATCH_RECOGNIZE row-scoped aggregate provider reached virtual or unbound row {current_rel}"
                );
            }
            // Keep argument allocations across rows. The transition's symbol
            // decides which empty slots to fill.
            // Program construction validates that aggregate IDs match slice positions.
            let program_count = self.matcher.program.aggregate_programs().len();
            let buffers = &mut self.state.scratch.pre_evaluated_aggs;
            let additional = program_count.saturating_sub(buffers.len());
            buffers.try_reserve(additional).map_err(|error| {
                datafusion::common::DataFusionError::ResourcesExhausted(format!(
                    "MATCH_RECOGNIZE could not reserve aggregate argument slots: {error}"
                ))
            })?;
            let mut program_work =
                crate::execution::common::progress::CoarseWorkCounter::new();
            let preparation_result = (|| {
                for aggregate_index in 0..program_count {
                    if aggregate_index == buffers.len() {
                        buffers.push(Vec::new());
                    } else {
                        clear_argument_slot(
                            &mut buffers[aggregate_index],
                            &self.state.argument_memory,
                        );
                    }
                    program_work.complete_one(report_completed_work)?;
                }
                Ok(())
            })();
            program_work.finish_result(preparation_result, report_completed_work)?;
        } else {
            // The virtual partition-end row must also release the last physical row.
            self.state.clear_argument_arrays();
        }

        Ok(())
    }

    #[inline(always)]
    fn current_collection_row_idx(&self, partition_len: usize) -> Result<usize> {
        let partition_row_idx = self.current_row.min(partition_len.saturating_sub(1));
        let collection_row_idx = self.collection_row_idx(partition_row_idx)?;
        if collection_row_idx >= self.input_buffer.num_rows() {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE row coordinate {collection_row_idx} is outside the buffered input"
            );
        }
        Ok(collection_row_idx)
    }

    fn current_global_row_idx(&self, partition_len: usize) -> Result<usize> {
        self.current_collection_row_idx(partition_len)?
            .checked_add(self.global_row_offset)
            .ok_or_else(|| {
                datafusion::common::DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE global row coordinate exceeds the platform usize boundary"
                        .to_string(),
                )
            })
    }

    /// Validate the requested row even on cache hits. Only a miss needs a location.
    fn uncached_row_location(
        &self,
        collection_row_idx: usize,
    ) -> Result<Option<(usize, usize)>> {
        let current_abs = self.collection_row_idx(self.current_row)?;
        if collection_row_idx != current_abs {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE row-scoped aggregate provider requested row {collection_row_idx} while bound to {current_abs}"
            );
        }
        if self.cached_batch.is_some() {
            return Ok(None);
        }
        let Some(location) = self.cached_batch_location else {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE row-scoped aggregate provider reached virtual or unbound row {collection_row_idx}"
            );
        };
        Ok(Some(location))
    }

    /// Ensure that the current physical row has one cached one-row batch.
    ///
    /// Branch-heavy fallback evaluation then borrows this same container across
    /// repeated predicate probes instead of cloning its column vector.
    fn ensure_single_row_batch(
        &mut self,
        collection_row_idx: usize,
        report_completed_work: &mut impl FnMut(usize) -> Result<()>,
    ) -> Result<()> {
        let Some(location) = self.uncached_row_location(collection_row_idx)? else {
            return Ok(());
        };
        cache_single_row_batch(
            &mut self.cached_batch,
            self.input_buffer,
            location,
            report_completed_work,
        )
    }

    #[inline]
    pub fn check_cache(
        &self,
        sym_id: SymbolId,
        match_start_row: AbsoluteRow,
        excluded: bool,
    ) -> Option<TransitionDecision> {
        let entry = self.state.define_cache_state.define_cache[sym_id.index()];
        (entry.generation == self.define_cache_gen
            && entry.match_start == match_start_row
            && entry.excluded == excluded)
            .then_some(entry.outcome)
    }

    #[inline]
    pub fn cache_result(
        &mut self,
        sym_id: SymbolId,
        match_start_row: AbsoluteRow,
        excluded: bool,
        outcome: TransitionDecision,
    ) {
        self.state.define_cache_state.define_cache[sym_id.index()] = DefineCacheEntry {
            match_start: match_start_row,
            generation: self.define_cache_gen,
            excluded,
            outcome,
        };
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::MatchRecognizeConfig;
    use crate::core::{AggregateId, NormalizedPattern, Pattern, Symbol};
    use crate::execution::common::progress::CoarseWorkCounter;
    use crate::execution::matching::build_test_matcher;
    use crate::execution::matching::program::contracts::AggregateProgram;
    use crate::execution::matching::row_loop::provider::ValueProvider;
    use crate::execution::matching::test_symbol_programs_for_automaton;
    use crate::nfa::CompiledAutomaton;
    use crate::planning::{AccumulatorInputMode, ManagedAggregateBackend};
    use datafusion::arrow::array::{BooleanArray, Int64Array};
    use datafusion::arrow::compute::SortOptions;
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion::common::DFSchema;
    use datafusion::execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryPool,
    };
    use datafusion::functions_aggregate::count::count_udaf;
    use datafusion::functions_aggregate::first_last::first_value_udaf;
    use datafusion::logical_expr::expr::{AggregateFunction, AggregateFunctionParams};
    use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
    use datafusion::logical_expr::{ColumnarValue, Volatility, col, create_udf};
    use datafusion::physical_expr::aggregate::AggregateExprBuilder;
    use datafusion::physical_expr::execution_props::ExecutionProps;
    use datafusion::physical_expr::expressions::{Column, Literal};
    use datafusion::physical_expr::{
        PhysicalExpr, PhysicalSortExpr, create_physical_expr,
    };
    use std::sync::Arc;

    const ARGUMENT_BYTES: usize = 64 * 1024;

    fn argument_fixture(kind: &str, order_by: bool) -> (PatternMatcher, BatchCollection) {
        let schema = Arc::new(Schema::new(vec![
            Field::new("__mr_symbol_a", DataType::Boolean, false),
            Field::new("value", DataType::Int64, false),
            Field::new("agg", DataType::Int64, false),
        ]));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(BooleanArray::from(vec![true, true])),
                Arc::new(Int64Array::from(vec![1, 2])),
                Arc::new(Int64Array::from(vec![0, 0])),
            ],
        )
        .unwrap();
        let argument: Arc<dyn PhysicalExpr> = if kind == "literal" {
            Arc::new(Literal::new(ScalarValue::Utf8(Some(
                "x".repeat(ARGUMENT_BYTES),
            ))))
        } else {
            let returns_array = kind == "array";
            let udf = create_udf(
                "large_argument",
                vec![DataType::Int64],
                DataType::Utf8,
                Volatility::Immutable,
                Arc::new(move |_| {
                    let scalar = ScalarValue::Utf8(Some("x".repeat(ARGUMENT_BYTES)));
                    if returns_array {
                        Ok(ColumnarValue::Array(scalar.to_array_of_size(1)?))
                    } else {
                        Ok(ColumnarValue::Scalar(scalar))
                    }
                }),
            );
            create_physical_expr(
                &udf.call(vec![col("value")]),
                &DFSchema::try_from(schema.as_ref().clone()).unwrap(),
                &ExecutionProps::new(),
                &PhysicalPlanningContext::default(),
            )
            .unwrap()
        };
        // COUNT discards ORDER BY; FIRST_VALUE exercises retained sort keys.
        let aggregate = if order_by {
            first_value_udaf()
        } else {
            count_udaf()
        };
        let mut builder = AggregateExprBuilder::new(
            Arc::clone(&aggregate),
            vec![if order_by {
                Arc::new(Column::new("value", 1)) as Arc<dyn PhysicalExpr>
            } else {
                Arc::clone(&argument)
            }],
        )
        .schema(Arc::clone(&schema))
        .alias("agg");
        if order_by {
            builder = builder.order_by(vec![PhysicalSortExpr {
                expr: argument,
                options: SortOptions::default(),
            }]);
        }
        let program = AggregateProgram::try_new(
            AggregateId::try_new(0, 1).unwrap(),
            Arc::new(builder.build().unwrap()),
            AggregateFunction {
                func: aggregate,
                params: AggregateFunctionParams {
                    args: vec![],
                    distinct: false,
                    filter: None,
                    order_by: vec![],
                    null_treatment: None,
                },
            },
            ManagedAggregateBackend::Accumulator,
            AccumulatorInputMode::Batch,
            false,
            ResolvedInputColumn::new_validated(2),
            None,
            schema.as_ref(),
        )
        .unwrap();
        let pattern = NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())));
        let compiled =
            Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()]).unwrap());
        let predicate: Arc<dyn PhysicalExpr> =
            Arc::new(Literal::new(ScalarValue::Boolean(Some(true))));
        let symbols = test_symbol_programs_for_automaton(
            &compiled,
            &[(
                SymbolId::try_new(1, compiled.num_symbols()).unwrap(),
                predicate,
            )],
            1,
        );
        let matcher = build_test_matcher(
            Arc::clone(&schema),
            pattern,
            compiled,
            &MatchRecognizeConfig::default(),
            move |input| {
                input.aggregate_programs = vec![program];
                input.symbols.symbol_programs = symbols;
            },
        )
        .unwrap();
        (
            matcher,
            BatchCollection::try_new(vec![batch], schema).unwrap(),
        )
    }

    fn evaluate_argument(engine: &mut AggregateEngine<'_, '_>) -> Result<()> {
        let mut provider = ValueProvider::Row {
            arguments: &mut engine.state.scratch.pre_evaluated_aggs,
            argument_memory: &engine.state.argument_memory,
            programs: engine.matcher.program.aggregate_programs(),
            cached_batch: &mut engine.cached_batch,
            input: engine.input_buffer,
            location: engine.cached_batch_location.unwrap(),
            symbol_id: None,
            symbol_name_arrays: &[],
        };
        provider
            .evaluate_args(
                AggregateId::try_new(0, 1).unwrap(),
                &mut CoarseWorkCounter::new(),
                &mut |_| Ok(()),
            )
            .map(|_| ())
    }

    #[test]
    fn argument_memory_survives_resume_and_releases_at_row_and_partition_boundaries() {
        for kind in ["literal", "scalar", "array"] {
            for order_by in [false, true] {
                let (matcher, input) = argument_fixture(kind, order_by);
                let pool: Arc<dyn MemoryPool> =
                    Arc::new(GreedyMemoryPool::new(1024 * 1024));
                let memory = MemoryConsumer::new("argument-test").register(&pool);
                let mut state = AggregateEngineState::new(memory, 0);
                let mut engine = AggregateEngine::new(
                    &matcher,
                    matcher.program.base_variant(),
                    &input,
                    &[],
                    &mut state,
                    0,
                    0,
                    0,
                    1,
                );
                engine.update_row(0, 2, 0, &mut |_| Ok(())).unwrap();
                evaluate_argument(&mut engine).unwrap();
                let retained = pool.reserved();
                assert!(retained >= ARGUMENT_BYTES);
                let last = engine.state.scratch.pre_evaluated_aggs[0].last().unwrap();
                let weak = Arc::downgrade(last);
                let payload_bytes: usize = engine.state.scratch.pre_evaluated_aggs[0]
                    .iter()
                    .map(|array| array.get_array_memory_size())
                    .sum();
                assert_eq!(retained, payload_bytes);
                // A cooperative pause drops the borrowed engine, keeping scan state.
                drop(engine);
                assert_eq!(pool.reserved(), retained);
                let mut engine = AggregateEngine::new(
                    &matcher,
                    matcher.program.base_variant(),
                    &input,
                    &[],
                    &mut state,
                    0,
                    0,
                    0,
                    1,
                );
                engine.resume_row(0, 0).unwrap();
                evaluate_argument(&mut engine).unwrap();
                assert_eq!(pool.reserved(), retained);
                assert!(std::ptr::eq(
                    weak.as_ptr(),
                    Arc::as_ptr(
                        engine.state.scratch.pre_evaluated_aggs[0].last().unwrap()
                    ),
                ));
                engine.update_row(1, 2, 0, &mut |_| Ok(())).unwrap();
                assert!(weak.upgrade().is_none());
                assert_eq!(pool.reserved(), 0);
                evaluate_argument(&mut engine).unwrap();
                engine.update_row(2, 2, 0, &mut |_| Ok(())).unwrap();
                assert_eq!(pool.reserved(), 0);
                engine.update_row(0, 2, 0, &mut |_| Ok(())).unwrap();
                evaluate_argument(&mut engine).unwrap();
                engine.state.reset();
                assert_eq!(pool.reserved(), 0);
                evaluate_argument(&mut engine).unwrap();
                engine.state.reset_partition_generation();
                assert_eq!(pool.reserved(), 0);
                engine.update_row(0, 2, 0, &mut |_| Ok(())).unwrap();
                evaluate_argument(&mut engine).unwrap();
                drop(engine);
                drop(state);
                assert_eq!(pool.reserved(), 0);
            }
        }
    }
}